> I have a question about zombies. My book says you should get rid of
> zombies like this when calling fork():
> int n, p;
> n=fork();
> ...
> if (n==0) {
> /*do child stuff*/
> }
> else if (n > 0) {
> /*do parent stuff*/
> wait(&p);
> }
> And that this should kill any zombies. Is that correct?
If the parent doesn't call wait(), then a terminating child process will have
it's exit status stored by the kernel until either the parent terminates or
calls wait(). This wastes resources, so it is generally best to call wait()
in the parent after the fork(). If you don't want to wait(), then a neat
trick is to call fork() from the child and have the first child terminate.
This means that the second child has no parent PID. It is then 'adopted'
by init, and no zombie is created when the child terminates. The original
parent simply has to wait() for the first child, which returns almost
immediately as it just fork()'s and exit()'s.
Quote:> And why do some people ignore SIG_CHLD like this:
> signal(SIG_CHLD, SIG_IGN);
> in programs that call fork()? Why ignore SIG_CHLD? When does a program
> recieve a SIG_CHLD, and does that cause a process to be a zombie?
Ignoring SIGCHLD, which is the signal generated when a child dies, implies
that the parent is not interested in the exit status of it's children.
Therefore the kernel doesn't bother storing the status - and no zombies
are created for that process.
Chris