| Randal L. Schwartz 2006-12-24, 9:58 pm |
| >>>>> "Kelly" == Kelly Jones <kelly.terry.jones@gmail.com> writes:
Kelly> I want to use system() (or `command`) to run an external command from
Kelly> my Perl script. However, if the external command takes more than 30
Kelly> seconds (for example) to run, I want to kill it, and move on with the
Kelly> rest of my Perl script. How do I do this?
You'll have to manage the forking yourself, and then have the parent
kill the child if it doesn't finish within your time.
Something like:
my $result = eval {
my $kidpid = open my $kidhandle, "-|";
defined $kidpid or die "Cannot fork: $!";
if ($kidpid) { # I am the parent:
alarm(30);
local $ARGV{ALRM} = sub {
kill 15, $kidpid;
waitpid $kidpid;
die "timeout";
};
my $buf;
$buf .= $_ while <$kidhandle>;
alarm(0);
$buf;
} else { # I am the kid:
exec "whatever", "command", "you", "want";
die "Cannot find whatever: $!";
}
}; die $@ unless $@ =~ /timeout/;
That's untested, but probably pretty close.
--
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!
|