linux - Why zombie processes exist? -


wikipedia says "a child process terminates never waited on parent becomes zombie process." run program:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> int main() {     pid_t pid, ppid;     printf("hello world1\n");     pid=fork();     if(pid==0)     {         exit(0);         }     else     {         while(1)         {         printf("i parent\n");         printf("the pid of parent %d\n",getpid());         printf("the pid of parent of parent %d\n",getppid());                 sleep(2);         }     } } 

this creates zombie process, can't understand why zombie process created here?

the output of program is

hello world1 parent pid of parent 3267 pid of parent of parent 2456 parent pid of parent 3267 pid of parent of parent 2456 parent .... ..... 

but why "child process terminates not waited on parent" in case?

in code, zombie created on exit(0) (comment arrow below):

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

why? because never waited on it. when calls waitpid(pid), returns postmortem information process, exit code. unfortunately, when process exited, kernel cannot dispose of process entry, or return code lost. waits wait on it, , leaves process entry around if not occupy memory except entry in process table - called zombie.

you have few options avoid creating zombies:

  1. add waitpid() somewhere in parent process. example, doing help:

    pid=fork(); if (pid==0) {     exit(0);     } else {     waitpid(pid);  // <--- call reaps zombie     // parent code ... } 
  2. perform double fork() obtain grandchild , exit in child while grandchild still alive. grandchildren automatically adopted init if parent (our child) dies, means if grandchild dies, automatically waited on init. in other words, need this:

    pid=fork(); if (pid==0) {     // child     if (fork()==0) {         // grandchild         sleep(1); // sleep bit let child die first         exit(0);  // grandchild exits, no zombie (adopted init)     }     exit(0);      // child dies first } else {      waitpid(pid);  // still need wait on child avoid zombified      // parent code ... } 
  3. explicitly ignore sigchld signal in parent. when child dies, parent gets sent sigchld signal lets react on children death. can call waitpid() upon receiving signal, or can install explicit ignore signal handler (using signal() or sigaction()), make sure child not become zombie. in other words, this:

    signal(sigchld, sig_ign); // <-- ignore child fate, don't let become zombie pid=fork(); if (pid==0) {     exit(0); // <--- zombie should not created here } else {      // parent code ... } 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -