in reply to For all your forking needs..

It makes sense to me. I'm not sure what you intended your logic to be, but it's a little confused at the moment. Try this:
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 { # $pid == 0, we're a kid, so what do we want to do? &doit($_); exit(0); # free this pid }
The first time through your loop, $npids is less than $MAX_PROCESSES, but $pid is defined (both in the parent and in the child), so it takes the third option. The parent (!!) goes to do_it(), sleeps for five seconds, and then exits. Oops.

I figure you probably want the children to exit. The one good way of telling the parent from the child is the value of $pid. If it's positive, you're in the parent. If it's zero, you're in a child. If it's undefined, the fork failed. (I'd move the failure code to the fork() statement.)

I can't figure out where AgentM got his comment, though. There's nothing in the newest edition of Programming Perl about wait being deprecated, and waitpid takes a different approach.

Replies are listed 'Best First'.
RE: Re: For all your forking needs..
by reyjrar (Hermit) on Oct 13, 2000 at 20:12 UTC
    heh.. I knew something was wrong, and as it turns out, in the production version, the one with all the real variables and processes, I actually did code the if elsif else correctly, just mangled it when I made that test program! :)
    thanks for catching that for me and letting me know where I went wrong..
    -brad.