in reply to Re^5: Timeout and kill
in thread Timeout and kill

I am still struggling very much with killing the process once it has timed out. This is what I have:
sub runFile2 { local($fileName, $timeout) = @_; my $child_pid; local $SIG{ALRM} = sub { $didTimeout=1; print OUTPUT "timeout"; print OUTPUT "-", $child_pid; kill 9, $child_pid; }; if ($child_pid = fork ) { # create child $didTimeout=0; alarm $timeout; $start=gettimeofday(); waitpid($child_pid, 0); # Wait for child to terminate alarm 0; $end=gettimeofday(); if($didTimeout==0) { print OUTPUT $end - $start; } else { kill 9, $child_pid; } } elsif (defined $child_pid) { $cmd = "$solver1 $fileName >> output.txt"; exec ($cmd); exit; } else { # Something terrible has happened, as fork failed die "Cannot fork!\n"; } }
It may not be the best way because I've just been trying anything I can find. The code will timeout the function, but not kill it. Any suggestions? Help would be greatly appreciated. I've tried everything I can find online without success. Thanks!

Replies are listed 'Best First'.
Re^7: Timeout and kill
by nelson64 (Initiate) on Mar 23, 2012 at 02:06 UTC
    Oops I posted the wrong version of the code:
    sub runFile { local($fileName, $timelimit) = @_; my $child_pid; local $SIG{ALRM} = sub { $didTimeout=1; print OUTPUT "timeout"; print OUTPUT "-", $child_pid; kill $child_pid, 9; }; if ($child_pid = fork ) { # create child waitpid($child_pid, 0); # Wait for child to terminate } elsif (defined $child_pid) { alarm $timelimit; $cmd = "time $solver1 $fileName >> output.txt"; exec ($cmd); alarm 0; exit; } else { # Something terrible has happened, as fork failed die "Cannot fork!\n"; } }
    This code times out the function but allows it to still run in the background.