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:
add
waitpid()somewhere in parent process. example, doing help:pid=fork(); if (pid==0) { exit(0); } else { waitpid(pid); // <--- call reaps zombie // parent code ... }perform double
fork()obtain grandchild , exit in child while grandchild still alive. grandchildren automatically adoptedinitif parent (our child) dies, means if grandchild dies, automaticallywaited oninit. 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 ... }explicitly ignore sigchld signal in parent. when child dies, parent gets sent
sigchldsignal lets react on children death. can callwaitpid()upon receiving signal, or can install explicit ignore signal handler (usingsignal()orsigaction()), 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
Post a Comment