I am running a perl script on a Linux host. I\'m trying to write a script that forks, where the child starts a program that takes forever and the parent times out after 5 s
Should be something like this. This isn't following best practices, but it should help you with your problem...
#!/usr/bin/perl
use warnings;
use strict;
use POSIX qw(:sys_wait_h);
my $timeOut = 5;
$SIG{ALRM} = \&timeout;
$SIG{CHLD} = 'IGNORE',
alarm($timeOut);
my $childPid = fork();
if ($childPid) {
while(1) {
print "[$$]: parent...\n";
sleep(2);
}
}else {
# I am the child - do something that blocks forever
while(1){
print "[$$]: child...\n";
sleep(2);
}
exit;
}
sub timeout {
print "killing $childPid\n";
print "###\n" . `ps -ef | grep -v grep | grep perl` . "###\n";
if ( ! (waitpid($childPid, WNOHANG)) ) {
print "killing $childPid...\n";
kill 9, $childPid;
die "[$$]: exiting\n";
}
}
OUTPUT:
$ forktest.pl
[24118]: parent...
[24119]: child...
[24118]: parent...
[24119]: child...
[24118]: parent...
[24119]: child...
killing 24119
###
cblack 24118 12548 0 14:12 pts/8 00:00:00 /usr/bin/perl ./forktest.pl
cblack 24119 24118 0 14:12 pts/8 00:00:00 /usr/bin/perl ./forktest.pl
###
killing 24119...
[24118]: exiting