Index
Home
About
Blog
From: Douglas A. Gwyn <gwyn@ix.netcom.com>
Newsgroups: comp.lang.c
Subject: Re: Terminating a child process
Date: Mon, 13 Oct 1997 00:18:50 GMT
The main problem is that you neglected to wait() on the children; so long
as their parent exists, terminated children remain in a "zombie" state so
that there is a place to keep their exit status, which is made available
to the wait()er.
When they have been "orphaned", i.e. their parent has terminated, they
are inherited by a "reaper" process (traditionally part of init, PID#1),
which quickly lays them to rest by wait()ing on them. In cases where the
parent does not find it convenient to wait on the children, a useful
trick is to make them grandchildren instead, with the intermediate child
process immediately dying; as just described, that means that the
children will be immediately inherited by PID#1, so when they terminate
they won't be zombies for more than an instant.
if ((pid=fork())==0)
// child process
if ((pid=fork())>0)
_exit(0); // child suicides after spawning
else if (pid<0) // error
handle_failure_to_fork(pid);
else { // pid==0 // grandchild
do_slave_processing();
_exit(0); // status sent to PID#1
}
else // parent process
if (pid<0) // error
handle_failure_to_fork();
else // wait for (immediate) suicide of child
while (waitpid(pid,&status,0)<0 && errno==EINTR)
; // wait interrupted by signal, try again
Index
Home
About
Blog