perllearner has asked for the wisdom of the Perl Monks concerning the following question:

I have forked process running 3 different test process within a perl script. Each of these process runs for a few hours (forked). All the tests are supposed to finish before exiting the forked process and later publish the files. I am using "wait" to do this to avoid zombies. However intermittenly the "wait" doesnt seem to be very robust, since the forked process exits prematurely and the logs gets published (unfinished). I see in the background the zombie process A, B and C still running. Can anyone tell where is the issue. Here is the code I have put together:
if ($pid = fork()) { if ($pid2 = fork()) { <process A>; } else { <process B>; exit} } else { <process C> exit; } 1 while wait() > 0; <publish files>

Any clues to why this is happening would be appreciated. Is the wait() command all messed up? thanks

Replies are listed 'Best First'.
Re: fork exits prematurely leaving zombies
by Steve_p (Priest) on May 11, 2004 at 19:20 UTC

    My forking is a bit rusty, so hopefully, I'm getting this right. Since process A is the parent of process B, there should be a wait there. Otherwise if process A finishes, it will wait on process C only. So, if process C finishes before process B, you'll get a zombie. The following may work a bit better.

    if ($pid = fork()) { if ($pid2 = fork()) { <process A>; waitpid $pid2, 0; } else { <process B>; exit; } waitpid $pid, 0; } else { <process C> exit; }
      My forking is a bit rusty
      This is so rife with comedic possibility...

      thor

Re: fork exits prematurely leaving zombies
by zude (Scribe) on May 11, 2004 at 22:57 UTC
    So the parent forks C, then forks B, then does A. When A is finished, then B and C will be reaped, meanwhile if they are already done then they are zombies.

    Would be cleaner to:

    if (!fork) { <process A>; exit } if (!fork) { <process B>; exit } if (!fork) { <process C>; exit } # parent waits for A, B, and C 1 while wait() > 0;
      thanks zude and steve for your responses. i think i now got it working (hopefully).
Re: fork exits prematurely leaving zombies
by gri6507 (Deacon) on May 11, 2004 at 19:06 UTC
    How do you start your processes? If they are started in the background, then the child could return without waiting for the process to complete. Also, if your process terminated before creating the file to publich, then, of course, there would be nothing to publish.
      thanks for your reply. sorry for not being clear earlier. the processes A and B are two additional perl scripts being run. And process C is a C-program. All of them are essentially running in background. Somehow i dont see the early exit at all times, but about 50% of the time.

      Any other ways I could wait till a background process is complete.