Discussion:
fork twice to prevent zombie process
(too old to reply)
b***@gmail.com
2007-01-31 02:04:34 UTC
Permalink
Hi,

I read the Unix Programming Faq, there are some statements on how to
prevent zombie process,

1.6.2 How do I prevent them from occuring?
------------------------------------------

Another approach is to `fork()' *twice*, and have the immediate child
process exit straight away. This causes the grandchild process to be
orphaned, so the init process is responsible for cleaning it up. For
code
to do this, see the function `fork2()' in the examples section.


anyone can tell me why fork twice is needed?

thanks
Paul Pluzhnikov
2007-01-31 02:34:32 UTC
Permalink
Post by b***@gmail.com
anyone can tell me why fork twice is needed?
Parent fork()s child C1 and immediately wait()s for it.
Child C1 immediately fork()s child C2 and exit()s.
Parent P collects C1 exit status and continues doing whatever it
needs to do.

Now C1 can't become a zombie -- it has exited and has been waited
for by P.

C2 can't become a zombie either -- it's parent (C1) has exited,
so C2 is an orphan.

Orphans on UNIX get inherited by process 1 (init).
Process 1 is constantly waiting for any childred that might exit
(that's one of its jobs). When C2 exits, its exit status gets
collected by init -- C2 doesn't become zombie.

Cheers,
--
In order to understand recursion you must first understand recursion.
Remove /-nsp/ for email.
baumann@pan
2007-01-31 02:45:05 UTC
Permalink
Post by Paul Pluzhnikov
Post by b***@gmail.com
anyone can tell me why fork twice is needed?
Parent fork()s child C1 and immediately wait()s for it.
Child C1 immediately fork()s child C2 and exit()s.
Parent P collects C1 exit status and continues doing whatever it
needs to do.
Now C1 can't become a zombie -- it has exited and has been waited
for by P.
C2 can't become a zombie either -- it's parent (C1) has exited,
so C2 is an orphan.
Orphans on UNIX get inherited by process 1 (init).
Process 1 is constantly waiting for any childred that might exit
(that's one of its jobs). When C2 exits, its exit status gets
collected by init -- C2 doesn't become zombie.
Cheers,
--
In order to understand recursion you must first understand recursion.
Remove /-nsp/ for email.
How about if parent immediately exits after child C1 forks(let the C1
be the orphan, parent process are not planing to do anything else)?
Paul Pluzhnikov
2007-01-31 03:29:00 UTC
Permalink
Post by ***@pan
How about if parent immediately exits after child C1 forks(let the C1
be the orphan, parent process are not planing to do anything else)?
If the parent doesn't need to do anything else, then it should simply
execute the code that child would have executed after fork.

If for some reason a child is still desired, then fork()ing once
and having the parent exit is sufficient to prevent the child from
becoming a zombie.

Cheers,
--
In order to understand recursion you must first understand recursion.
Remove /-nsp/ for email.
Loading...