Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to make a subroutine that I pass a command to, the sub forks a new process, runs the command, then kills the process. Here is what I have so far:
sub runnewproc { $pid = fork(); if ($pid == 0) { system("$_[0]"); } else { sleep 1; kill $pid; } }
This isn't working. Any help would be appreciated. Thanks.

Replies are listed 'Best First'.
(tye)Re: Fork Problem
by tye (Sage) on Dec 08, 2000 at 10:29 UTC

    As was already mentioned briefly, Win32 doesn't support fork(). Perl 5.6 has a simulated fork() but it is brand new and still pretty buggy.

    However, there are much easier ways to run an external programs and most of these are fully supported in Perl under Win32. But since you want to kill the process later, I suspect your only real choice is to use Win32::Process. "perldoc Win32::Process" should present you with the documentation for this module.

            - tye (but my friends call me "Tye")
Re: Fork Problem
by Fastolfe (Vicar) on Dec 08, 2000 at 02:23 UTC
    Define "isn't working". Do you get an error message? What do you expect your script to do that it isn't doing? What is it doing instead?

    Off-hand, your script is forking and staying forked. Your system call will return when the command is completed, and then continue execution of your script just as if it were the parent (at least until the parent kills it). Have you verified that the script will successfully do a system call with that argument without problems?

    I'm also tempted to ask you what you're trying to do here. Is your sleep/kill combo an attempt at enforcing a timeout? Consider alarm in the child process for that. Either way, you're going to be a lot better off putting an exit after your system call, or use exec instead of system (checking to be sure exec doesn't return in an error).

    If this doesn't help you, we need more information.

      I'm launching a Windows based program with this script.

      exec('C:\Progra~1\Blah\Blah');

      It works; it runs the program fine. This program is not command line, so it opens in its own window. I then need to run another program after the first one has launched.

        I'm launching a Windows based program with this script.
        That's your problem, then. Windows does not allow you to fork. You'll need to simulate fork, but I wouldn't guarantee the results. Assuming you're running ActivePerl, you can read about this here.

        Cheers,
        Ovid

        Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.