Why zombie processes exist? Why zombie processes exist? unix unix

Why zombie processes exist?


In your code, zombie is created on exit(0) (comment with arrow below):

pid=fork();if (pid==0) {    exit(0);  // <--- zombie is created on here} else {    // some parent code ...}

Why? Because you never waited on it. When something calls waitpid(pid), it returns postmortem information about process, like its exit code. Unfortunately, when process exited, kernel cannot just dispose of this process entry, or return code will be lost. So it waits for somebody to wait on it, and leaves this process entry around even if it does not really occupy any memory except for entry in process table - this is exactly what is called zombie.

You have few options to avoid creating zombies:

  1. Add waitpid() somewhere in the parent process. For example, doing this will help:

    pid=fork();if (pid==0) {    exit(0);    } else {    waitpid(pid);  // <--- this call reaps zombie    // some parent code ...}
  2. Perform double fork() to obtain grandchild and exit in child while grandchild is still alive. Grandchildren will be automatically adopted by init if their parent (our child) dies, which means if grandchild dies, it will be automatically waited on by init. In other words, you need to do something like this:

    pid=fork();if (pid==0) {    // child    if (fork()==0) {        // grandchild        sleep(1); // sleep a bit to let child die first        exit(0);  // grandchild exits, no zombie (adopted by init)    }    exit(0);      // child dies first} else {     waitpid(pid);  // still need to wait on child to avoid it zombified     // some parent code ...}
  3. Explicitly ignore SIGCHLD signal in parent. When child dies, parent gets sent SIGCHLD signal which lets it react on children death. You can call waitpid() upon receiving this signal, or you can install explicit ignore signal handler (using signal() or sigaction()), which will make sure that child does not become zombie. In other words, something like this:

    signal(SIGCHLD, SIG_IGN); // <-- ignore child fate, don't let it become zombiepid=fork();if (pid==0) {    exit(0); // <--- zombie should NOT be created here} else {     // some parent code ...}