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

Hi,

I’ve two Perl programs: ‘P1.pl’ and ‘P2.pl’.
I would like to execute ‘P2.pl’ from ‘P1.pl’.
Once ‘P1.pl’ will execute ‘P2.pl’, I need to add a timer that will take 3 min.
If ‘P2.pl’ will not terminated after 3 Min. ‘P1.pl’ will kill ‘P2.pl’ and exit with error message
*** Incidentally – I'm not sure if it is important but the code in P2.pl script is including system command embedded.
Please advice.

Thanks.
  • Comment on Executing perl script from perl script.

Replies are listed 'Best First'.
Re: Executing perl script from perl script.
by almut (Canon) on Apr 22, 2009 at 09:38 UTC

    ...on Unix or Windows?

    On Unix, you could create a new process group (—> setpgrp) for P2.pl and its children (processes run via system), and then setup a timer, for example via alarm, that would kill the entire process group (send negative signal number with kill) when it hasn't completed on time...

    See Re^2: Killing children's of children for some sample code.

    Update: On Windows, there's Win32::Job and Win32::Process (the latter is used under the hood by the Proc::Background that cdarke mentioned).

    ___

    Side note:  for formatting your nodes, it's <br />, not </br>. Or even better, simply use <p> to tag whole paragraphs... in which case the browser will do the line wrapping within a paragraph all by itself.

Re: Executing perl script from perl script.
by cdarke (Prior) on Apr 22, 2009 at 11:20 UTC
Re: Executing perl script from perl script.
by doug (Pilgrim) on Apr 22, 2009 at 12:57 UTC
    Could p1 just set "alarm 180;" and have the signal handler do the "kill p2 if it still running" stuff?

      The problem with this standard approach is that it may leave orphaned children behind. Unless you set up a process group, you have no single 'handle' to all the processes that belong together. You only have the PID of the parent process that P1.pl directly created, but not of its children and grandchildren, etc. (and it's non-trivial, or at least cumbersome, to find them out).

      So what you would kill is just that one process. And there's no guarantee whatsoever that it will take care of 'cleaning up' by itself...