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

I use "system @args" to run a seperate program in Perl script and get the return by "$rc=Oxffff & system @args". However, sometimes the Perl script cannot notice the sub-process has done and get its return value. The Perl script just hang on there and wait till I kill it. Does anybody know what the problem is?

Replies are listed 'Best First'.
Re: system @args problem
by McDarren (Abbot) on Jan 18, 2006 at 07:41 UTC
    The usual way to deal with something like this is to wrap your system call in an eval block, and use an alarm to set a timeout. For example:
    my $timeout = 20; # or whatever is appropriate eval { local $SIG{ALRM} = sub { die "timedout" }; alarm $timeout; # Your system call goes here.... alarm 0; }; if ($@) { # $@ will contain error message, if any }

    Hope this helps,
    Darren :)

Re: system @args problem
by atcroft (Abbot) on Jan 18, 2006 at 05:35 UTC

    It would help to know what program and arguments you are passing, and if it always occurs with one/a few programs in particular, or all that you try it with.

    Some reasons I can think of off-hand include input is expected that isn't present, the process is taking longer than expected, resource limitations, the program doesn't like being run in that manner, or something similar-but without knowing more detail, it is hard to do more than just guess.

Re: system @args problem
by blazar (Canon) on Jan 18, 2006 at 08:10 UTC

    I doubt that the script "cannot notice the sub-process has done". More probably the process forked off with system does never actually return. In which case you may set up a timeout. This is usually done through eval and alarm. You should get plenty of examples by doing a search, so it's not worth repeating any here. If you have any specific problem, then ask again.

    PS: now that we told you 'bout eval, please use it only as necessary, and do not abuse it, especially in its string form, it's often frowned upon as Bad(TM), and there are good reasons why it is!