in reply to Launching an external process with a run-time limit

Hello, I use a function like this as my backtick replacement (with timeouts). I use alarm instead of fork & select.
sub texec { my $timeout = shift; my $out = []; eval { local $SIG{ALRM} = sub { die "timeout\n" }; alarm ($timeout); # set timer .. hope the platform has signals my $cpid = open (my $fh, "-|") || exec (@_); $| = 1; # line buffer while (<$fh>) { chomp; push (@{$out}, $_); } close ($fh); alarm 0; # reset, we've got all the data and we're cool }; # If something died in the eval, return a ref to a list containing # the output as well as the die text. otherwise just the output. return (($@) ? [$out, $@] : $out); }
One downside is that I haven't manged to shave the yak to get capturing of both STDOUT and STDERR to work on both Windows and *n*x.

Usage is:

my $res = texec (10, "/usr/bin/ls", "-al", "/"); if (ref ($res->[0])) { print "Error while executing: $res->[1]\nCommand output:\n"; print Dumper ($res->[0]), "\n"; } else { print "Command output:\n"; print Dumper ($res), "\n"; }

Replies are listed 'Best First'.
Re^2: Launching an external process with a run-time limit
by Anonymous Monk on Oct 18, 2006 at 15:40 UTC
    my $cpid = open (my $fh, "-|") || exec (@_);
    Two things can fail here, and both times, you continue on if nothing has happened. The open may fail - if it does, the subroutine performs an exec, to never return (unless the exec fails). The exec might fail as well, meaning that the child executes the rest of the subroutine - and the rest of the program.
    $| = 1; # line buffer
    This unbuffers STDOUT. For the rest of the program. Now, your entire subroutine doesn't write the STDOUT, making the unbuffering pointless for the subroutine itself, and possibly damaging for the rest of the program.
    close ($fh);
    No checking of the return value? $fh is a pipe, and certain failures won't be reported until you close the pipe.

    Also, if the timeout is triggered, the parent is killed (inside an eval). However, the spawned process goes on. Now, you might be lucky and it will write something to the pipe, getting a SIGPIPE and not surviving that, but you ought to kill the process (whose PID you store in $cpid, which currently is unused).

Re^2: Launching an external process with a run-time limit
by TheFluffyOne (Beadle) on Oct 18, 2006 at 15:43 UTC
    Excellent, thanks for the code. It looks like this does what I need, though I'll have to see whether the STDOUT/STDERR capture is an issue. Cheers!