Skip to content

Instantly share code, notes, and snippets.

@icot
Created June 27, 2012 09:46
Show Gist options
  • Save icot/3003017 to your computer and use it in GitHub Desktop.
Save icot/3003017 to your computer and use it in GitHub Desktop.
Perl timed child process
#!/usr/bin/perl -w
use strict;
use POSIX;
my $MAX_EXEC_TIME = 10;
my $pid;
eval {
local $SIG{'ALRM'} = sub { die "timed out\n" };
alarm($MAX_EXEC_TIME);
print "Starting child process\n";
$pid = fork();
if ($pid) {
print "Child Pid = $pid\n";
waitpid $pid, 0;
}
else {
my $limit = 5;
my $cont = 0;
while ($cont <= $limit){
print("Doing work for $cont/$limit seconds\n");
sleep(1);
$cont ++;
}
exit 0;
}
};
if ($@) {
if ($@ eq "timed out\n") {
print "I timed out and killed pid $pid\n";
if ($pid) {
kill(15, $pid);
}
$pid = undef;
}
else {
print "something else happened: $@\n";
}
}
else {
print "Child process terminated as expected. I can keep going...\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment