Index Home About Blog
From: Douglas A. Gwyn <>
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
		else { // pid==0	// grandchild
			_exit(0);	// status sent to PID#1
	else	// parent process
		if (pid<0)	// error
		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