On Thu, Jan 16, 2003 at 02:10:48PM +1300, Carl Cerecke wrote:
> while (zombies && !child) {
fork() returns the PID of the new process in the parent, and returns 0
in the newly forked child. So the test in this while is wrong, it's
causing the subsequent fork()s to be called in the child.
The reason you don't see any zombies is because each process is the
child of another, e.g.:
<initial process>
<first child>
<second child>
<third child>
...
Or, a different view (using ``ps xl''):
UID PID PPID CPU PRI NI VSZ RSS WCHAN STAT TT TIME COMMAND
1000 28990 14485 0 10 20 80 500 nanosl S p0 0:00.01 ./zombie
1000 7017 28990 0 10 20 80 500 nanosl S p0 0:00.00 ./zombie
1000 31421 7017 0 10 20 80 500 nanosl S p0 0:00.00 ./zombie
1000 23905 31421 0 10 20 80 500 nanosl S p0 0:00.00 ./zombie
1000 8094 23905 0 10 20 80 500 nanosl S p0 0:00.00 ./zombie
1000 3027 8094 0 10 20 80 500 nanosl S p0 0:00.00 ./zombie
Note the PID compared to the Parent PID (PPID) in the above.
When a parent process dies, its children are reparented to init. What's
happening in this case is that the children of the initial process all
die at the same time, causing their children to be reparented to init,
and init will then wait() on them... thus, no zombies. Because all of
the child processes die at roughly the same time, the process teardown,
zombification, reparenting and wait()ing all happens too fast to see.
Here is a fixed version of the code:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int zombies = 4;
int child_pid = 0;
do {
child_pid = fork();
zombies--;
} while (zombies && child_pid != 0);
if (child_pid == 0) {
printf("child entry\n");
sleep(1);
printf("child exit\n");
_exit(0);
} else {
printf("parent entry\n");
sleep(10);
printf("parent exit\n");
}
}
Cheers,
-mjg
--
Matthew Gregan |/
/| [EMAIL PROTECTED]