use strict; use warnings; use feature 'say'; use POSIX ":sys_wait_h"; use Time::HiRes qw(usleep); my $maxProcs = 20; # Maximum number of processes to run concurrently my $countProcs = 0; # Keep track of how many are running my $finished = 0; # Flag variable my $startTime = time(); # Going to keep forking until now + 30 sub main { while ($countProcs < $maxProcs) { my $child = fork(); die "Cannot fork: $!" unless defined($child); if ($child == 0) { # Child process doStuff(); } else { $countProcs++; } } usleep(50); # The main process sleeps so not burning up cpu cycles # in a wait loop } sub doStuff { my $sleepTime = rand() * 10+3; #3-13 seconds printf("%i doing work for %.02f seconds\n",$$,$sleepTime); sleep $sleepTime; exit; } while (not $finished) { main(); #https://www.freebsd.org/cgi/man.cgi?query=waitpid&manpath=SuSE+Linux/i386+11.3 my $reaped = waitpid(-1,WNOHANG); # Wait for any child process without blocking if ($reaped) { say "$reaped reaped"; $countProcs--; } $finished = 1 if (time() > $startTime + 30); } while (wait() != -1) { usleep(50); }