Is it possible to implement some kind of timeout (time limit) for fork using Parallel::ForkManager ?
Basic Parallel::ForkManager script looks like this
use Parallel::ForkManager;
my $pm = Parallel::ForkManager->new( 10 );
for ( 1 .. 1000 ) {
$pm->start and next;
# some job for fork
$pm->finish;
}
$pm->wait_all_children();
I would like to limit time for “# some job for fork”. For example, if its not finished in 90 secs. then it (fork) should be killed/terminated.
I thought about using this but I have to say, that I dont know how to use it with Parallel::ForkManager.
EDIT
Thanks hobbs and ikegami. Both your suggestions worked….. but only in this basic example, not in my actual script :(.

These forks will be there forever and – to be honest – I dont know why. I use this script for couple of months. Didnt change anything (although many things depends on outside variables).
Every fork has to download a page from a website, parse it and save results to a file. It should not take more than 30 secs per fork. Timeout is set to 180 secs. Those hanging forks are totally random so its very hard to trace the problem. Thats why I came up with a temporary, simple solution – timeout & kill.
What could possibly disable (interrupt) your methods of timeout in my code ? I dont have any other alarm() anywhere in my code.
EDIT 2
One of the forks, was hanging for 1h38m and returned “timeout PID” – which is what I type in die() for alarm(). So the timeout works… but its late about 1h36,5m ;). Do you have any ideas?
Update
Sorry to update after the close, but I’d be remiss if I didn’t point out that Parallel::ForkManager also supports a
run_on_startcallback. This can be used to install a “child registration” function that takes care of thetime()-stamping of PIDs for you.E.g.,
The upshot is that, in conjunction with
run_on_waitas described below, the main loop of a P::FM doesn’t have to do anything special. That is, it can remain a simple$pm->start and next, and the callbacks will take care of everything else.Original Answer
Parallel::ForkManager’s
run_on_waithandler, and a bit of bookkeeping, can force hanging and ALRM-proof children to terminate.The callback registered by that function can be run, periodically, while the
$pmawaits child termination.(As others suggest, it’s better to have the children regulate themselves via
alarm(), but that appears intermittently unworkable for you. You could also resort to wasteful, gross hacks like having each child itselffork() or exec('bash', '-c', 'sleep 90; kill -TERM $PPID').)