fork problems (zombie children)

Andrew C. Esh (andrewes@andrewes.cnt.com)
Mon, 20 May 1996 08:50:26 -0500


Thomas Zerucha writes:
> What am I doing wrong? The following program:
>
> #include <signal.h>
> #include <sys/wait.h>
> main(){
> for(;;) {
> if( !fork() ) {
> exit(0); /* child, exit immediately */
> }
> sleep(1);
> }
> }
>
> when run with PID=8704 creates children that stay undead until the parent
> process terminates, e.g. from "ps -x":
>
> 8704 v14 8 0:00 ./forktest
> 8705 v14 8 0:00 (forktest) Z 8704
> 8707 v14 8 0:00 (forktest) Z 8704
> 8708 v14 8 0:00 (forktest) Z 8704
> 8710 v14 8 0:00 (forktest) Z 8704
> 8712 v14 8 0:00 (forktest) Z 8704
> 8714 v14 8 0:00 (forktest) Z 8704
> 8716 v14 8 0:00 (forktest) Z 8704
> 8717 v14 8 0:00 (forktest) Z 8704
>
> I ran out of virtual memory on my 32Mb machine on a different app (lynx)
> after lots of these were created.
>
>

The children *are* being created, and then they finish. The reason
they remain as zombies is because their exit status must be reported
to the main process. Since the main process is not doind a wait(2) on
them, they pile up waiting to report. The reason they finally die when
the main process exits is because they are removed by the system when
the PID group leader (the main prcoess) is killed. This is what allows
you to kill all processes in a group without having to hunt down each
one and kill it individually.

You need to read "Unix Network Programming", by W. Richard Stevens.

---
Andrew C. Esh			mailto:andrew_esh@cnt.com
Computer Network Technology	andrewes@mtn.org (finger for PGP key)
6500 Wedgwood Road		612.550.8000 (main)
Maple Grove MN 55311		612.550.8229 (direct)
http://www.cnt.com - CNT Inc. Home Page
http://www.mtn.org/~andrewes - ACE Home Page