in reply to Run and Stop another program in perl

fast:

If you use fork (on an operating system that supports it well), you can set up the I/O streams and fork off the task. Then you'll have the PID (process identifier) for the forked job, and you can kill it when you decide to. Something like:

my $child_PID = fork; if ($child_PID == 0) { # We're in the child process, so redirect I/O handles and run progr +am... close STDOUT; open STDOUT, '>', 'foobar.log' or die $!; exec 'foobar.exe', 'argument_1', 'second argument', 'etc...'; die "Couldn't find foobar.exe!"; # should never get here... } else { # We're in the parent, so wait a few seconds, and kill the child. sleep 10; kill 9, $child_PID; }

Untested code. Testing (and any repairs required) left as an exercise for the reader...

...roboticus

Replies are listed 'Best First'.
Re^2: Run and Stop another program in perl
by BrowserUk (Patriarch) on Aug 21, 2010 at 06:18 UTC

    Why would you use forking fork instead of the built-in forking open which works everywhere? :)

      BrowserUk:

      I don't normally tie programs together in perl, thus I rarely use fork or open to connect programs together. Hence, I just used the first one I thought of. As I'm a C/C++ programmer, fork naturally came to mind. Perhaps I'll think of open next time... ;^)

      ...roboticus

Re^2: Run and Stop another program in perl
by JavaFan (Canon) on Aug 21, 2010 at 08:42 UTC
    Funny that both you and BrowserUK decide to kill using SIGKILL. That's not very friendly, and not "the appropriate way" - it doesn't give the program a chance to shutdown gracefully (for instance, if the killed process would be a Perl program, sending it SIGKILL robs the program of its opportunity to run END blocks. Or to call DESTROY. Or to cleanly shut down database connections.). Send it a SIGTERM (often 15, but technically, it's architecture dependent - check $Config::Config{sig_name} if you want to cover portability issues).

      In my case, there is good reason for that. Did you notice the OPs program name: program.exe?

      On win32, it makes no difference. The following code does kill 15, but notice that it is reported by the terminatng process as sigbreak:

      Perl> $pid = open CMD, '-|', q[perl.exe -le"$SIG{TERM}=sub{print 'here +' }; $|++; print ++$i while sleep 1"] or die $!;; Perl> print scalar <CMD> for 1 .. 10;; 1 2 3 4 5 6 7 8 9 10 Perl> kill 15, $pid;; Terminating on signal SIGBREAK(21)

      The pseudo signals perl provides on win32 are useful, but limited. And bear very little resemblance to POSIX signal handling.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.