4th Floor, 4 Tabernacle Street London EC2A 4LU

Perl – Fork and Kill a System Process on Timeout

[perl]

$pid = open(PIPE, “$command |”) or die $!;
eval {
local $SIG{ALRM} = sub { die “TIMEOUT” };
alarm($timeout);
while (<PIPE>) {
$data = $_;
};
close(PIPE);
alarm(0);
};
if ($@) {
die $@ unless $@ =~ /TIMEOUT/;
kill 15, $pid;
close(PIPE);
$? ||= 9;
} else {
## Exit status from the child
my $child_exit = $? >> 8;
if ($child_exit != 0) {
# Bad Status
} else {
# Clean Exit
}
}
[/perl]