#!/usr/bin/perl use strict; my $MAX_PROCESSES=10; my $npids=0; for(1..15) { my $pid; print "Forking: $_\n"; sleep 1; $pid=fork(); if($pid > 0) { #we forked successfully $npids++; if($npids>=$MAX_PROCESSES) { my $wait=wait(); if($wait) { $npids--; } } elsif(undef $pid) { # we didn't fork successfully print "fork error!\n"; } else { #what do we want to do? &doit($_); exit(0); # free this pid } exit(0); # we shouldn't get to this point } } # if we have any stragglers, lets wait for them to finish. for(1..$npids){ my $wt=wait(); if($wt==-1){ #print "hey $!\n"; redo; } } sub doit { my $num = shift; sleep 5; print "$num DONE\n"; }