http://qs321.pair.com?node_id=541238


in reply to controlling child processes

It is easy to get these problems wrong, so I second using Parallel::ForkManager. In your solution you need to keep looping not only if there is more work to spawn, but also if there are children to reap. Update: That's confusing to read -- it just means you'll need to reap 3 children at the end.

I like to use a hash to maintain the children. Here's an untested solution, probably with bugs ...

use strict; use warnings; $SIG{CHLD} = 'IGNORE'; my $max_procs = 3; # don't use strings when you want numbers my @work = qw(fw1 fw2 fw3 fw4 fw5); my %kids; while (@work or keys %kids) { if (@work and $max_procs > keys %kids) { my $fw = shift @work; my $pid = fork; die "Can not fork!" if ! defined $pid; if ($pid) { $kids{$pid} = $fw; } else { exec "remotelogfile $fw logfile > /var/$fw.log"; die; } } else { my $pid = waitpid(-1, 0); delete $kids{$pid}; } }