in reply to fork n wait

I have a similar script that keeps a fixed number of children running at all times. Basically, you just set a variable for the number of kids out, then have the main script decrement that by one when a child exits (however you do it - I use signals, but see the caveats above). In your case, you need to have some code like this:
## Not real code! Very poor pseudo-code actually. :) $kids = 4; $kidsOUT=0; $SIG{CHLD} = \&ReapKids; for (1..$kids) { FORK or die if (child) { Do child things exit } else { $kidsOUT++; } } sub ReapKids { ## This detects when the kids are finished, somehow ## If signalling, verify the PID as well if (KidHasDied) { $KidsOUT--; } } { ## Second loop, runs when all kids from first are finished if ($KidsOUT) { ## Still waiting! sleep 10; redo; } } ## Same as above...spawn however many kids you need...
This is vey, very, rough code but should illustrate one way to do it.