MattGranger
Programmer
Hi, This is my first Perl project, and it's proved to be challenging. I'm trying to spawn off a number of child processes, record their PID's, and then later use that PID to kill the process off if it's been running past a given length of time. Easy eh? Use FORK eh? Wrote a test child, and set it to sleep for 45 seconds, but set it's timeout for 30. The parent process kept running OK, the child process ran OK. But the PID wasn't returned to the parent in the fork code until the child had completed execution, i.e. until after it's 45 second sleep, so I couldn't kill it off. I've considered using thread & detach, but thought forum guidance might yield the answer I seek. Here's the code snippet that launches the child:
sub runit {
# Grab the executable and the associated parameter line
my $which=shift;
my $params = shift;
FORK: {
if ($pid=fork()) {
return $pid;
# this is the parent, so return the pid
# everything below here is either the child or a very major
# system failure
}
elsif (defined $pid) {
if ($granularity) {log_message("Starting monitor $which $params");}
exec $which ." " .$params;
# shouldn't reach this unless exec fails
log_message("Failure starting monitor $which $params");
exit 0;
# exit, NOT return. We're the child process
}
elsif ($! == EAGAIN) {
sleep 3;
redo FORK;
}
else {
log_message("Fork failure starting monitor $which $params");
return 0;
}
}
Many thanks,
Matt
sub runit {
# Grab the executable and the associated parameter line
my $which=shift;
my $params = shift;
FORK: {
if ($pid=fork()) {
return $pid;
# this is the parent, so return the pid
# everything below here is either the child or a very major
# system failure
}
elsif (defined $pid) {
if ($granularity) {log_message("Starting monitor $which $params");}
exec $which ." " .$params;
# shouldn't reach this unless exec fails
log_message("Failure starting monitor $which $params");
exit 0;
# exit, NOT return. We're the child process
}
elsif ($! == EAGAIN) {
sleep 3;
redo FORK;
}
else {
log_message("Fork failure starting monitor $which $params");
return 0;
}
}
Many thanks,
Matt