in reply to Killing a system/exec/`` call if it times out

Here's a simple fork/exec with an alarm. It won't cleanup multiple processes so it must use the >1 arg version of exec. I think you might already know that exec with more than 1 argument avoids using sh.

#!/usr/bin/env perl use warnings; use strict; my $ksecs = 5; my $csecs = 10; my $sig = 2; my $pid = fork; die "fork: $!" unless(defined $pid); if($pid == 0){ exec 'sleep', $csecs; # >1 arg exec to avoid using sh die "failed to spawn command: $!"; } local $SIG{'ALRM'} = sub { kill $sig, $pid }; alarm $ksecs; waitpid $pid, 0; # waitpid sets $? alarm 0; # turn off alarm in case child finished before parent if($? == $sig){ # we killed it (or someone else sent the same signal) }elsif($?){ # child had another error or signal }

Replies are listed 'Best First'.
Re^2: Killing a system/exec/`` call if it times out
by Cagao (Monk) on Dec 01, 2011 at 23:57 UTC
    Cheers, but yeah, I'm looking for a "kill all children of this PID, and their children too"
      You are looking for Proc::Killfam. Many, if not most times, when you fork to run a program, you end up getting the shell pid of actual program you ran. So if you killfam 9 that toplevel shell, you should get them all.

      I'm not really a human, but I play one on earth.
      Old Perl Programmer Haiku ................... flash japh