You may also be expecting that get_pidof is returning the process id only of any running fork.pl programs, but you may have others -- for example, if you're editing fork.pl in the background, then get_pid can match it instead. So first of all, try passing a second argument to get_pidof:
which should cause it to find processes which exactly match fork.pl.my @pids = $get_pidof('fork.pl', 1);
Next of all, why are you decrementing $childcnt when the return from the wait is -1? According to perldoc -f wait:
Which means you probably want to decrement only when you get a value greater than zero for $completed_pid. Additionally, you are executing a blocking wait, so the wait will block until it succeeds, or returns -1 for "no more children". If you want to make it non-blocking, try something like this:wait Behaves like the wait(2) system call on your system: it + waits for a child process to terminate and returns the pid of + the deceased process, or "-1" if there are no child process +es. The status is returned in $?. Note that a return value of +"-1" could mean that child processes are being automatically + reaped, as described in perlipc.
while (1) { my $completed_pid = waitpid(-1, WNOHANG); if ($completed_pid == -1) { # No more children -- exit loop last; } if ($completed_pid > 0) { print "<parent>: $completed_pid is done; $childcnt running\n"; $childcnt--; sleep 1; } }
You'll also need use POSIX ":sys_wait_h"; at the top of the program. You can read more about non-blocking waits with perldoc -f waitpid.
Update: I discovered another possible reason why you're getting a negative $childcount when you use get_pidof() ... it's because get_pidof is itself spawning a process which is a child of fork.pl. This causes your program to wait for it and it decrements $childcount one too many times.
In reply to Re: get_pidof() messes with wait()?
by liverpole
in thread get_pidof() messes with wait()?
by rhumbliner
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |