Re: Killing a process that takes too long



Thanks Tom!

I replaced the system call with fork and exec and it works just the
way I want it to:

use warnings;
use strict;

my $pid;

eval {
local $SIG{ALRM} = sub {
print "Timed out\n";
kill 'INT', $pid;
die 'alarm';
};
alarm 5;
if ($pid = fork)
{
waitpid ($pid, 0);
}
else
{
exec ('sleep 45');
}
alarm 0;
};
die if $@ && $@ !~ /alarm/;
print "Exited normally.\n";

__END__

For my actual program, I had to do a bit more work because I have
semicolons and other shell stuff in the command (which seems not to do
so well with exec?), but I figured out a workaround.

So, thanks again!

- Jen


On 11/21/06, Tom Phoenix <tom@xxxxxxxxxxxxxx> wrote:
On 11/21/06, Jen Spinney <jen.spinney@xxxxxxxxx> wrote:

> I want to make a system call, and then kill the process if it takes
> too long.

> So, if I do a ps -af, I can see that my perl script is a goner, but
> the process spawned from the system call is still alive.

Yes; if you use system() to start a sub-process, you're letting perl
manage it; so there's no way to get the process-ID.

You may instead use fork and exec; this lets you use the process-ID to
manage the process directly. Be sure to use wait or waitpid to reap
the completed child process, so as not to leave zombies.

Is that what you needed? Hope this helps!

--Tom Phoenix
Stonehenge Perl Training

.



Relevant Pages