You pass the WNOHANG flag, which makes the call non-blocking. Remove this flag and waitpid will wait for 0% of the CPU until the child leaves.
If you take this approach, you can simplify the code. There is no need to quote until the child is completed, because the call to waitpid will do this for you:
for (my $i = 0; $i < $n; ++$i) { if ($children_pids[$i] > 0) { waitpid($children_pids[$i], 0); print "child done\n"; $children_pids[$i] = 0; } }
Alternatively, change the sleep call to wait one second. Then your program will check the finished children every second, without increasing the processor load.
source share