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 cy +cles # 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=SuS +E+Linux/i386+11.3 my $reaped = waitpid(-1,WNOHANG); # Wait for any child process wit +hout blocking if ($reaped) { say "$reaped reaped"; $countProcs--; } $finished = 1 if (time() > $startTime + 30); } while (wait() != -1) { usleep(50); }
Thanks Tye for providing the freebsd link which is great information for wait() vs waitpid and which flags to use. I guess that made more sense to me than the perldocs even though I see now I used waitpid exactly as it is in waitpid. Well in my defense it says "do a non-blocking wait for all pending zombie processes" but I guess that just applies to the way it is used in that code snippet.
I wanted "do a non-blocking wait for any pending zombie processes". The code example in waitpid seems to do the same thing as while (wait()!= -1) {}. Hopefully I used it correctly! Maybe I really should get that i-7 for christmas
In reply to Re: Forking multiple processes at once, but limiting how many at a time
by trippledubs
in thread Forking multiple processes at once, but limiting how many at a time
by jLinux
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |