operating system - How to avoid zombie processes? and what exactly init process does in this situation? -
how avoid zombie processes? , init process in situation?
i've seen program,but not able it: how program creates zombie process:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(void) { pid_t p = fork(); if (p != 0) { waitpid(p, null, 0); /* see if child had ended. */ sleep(1); /* wait 1 seconds child end. , eat away sigchld in case if arrived. */ pause(); /* suspend main task. */ } else { sleep(3); /* let child live tme before becoming zombie. */ } return 0; }
a child process turns zombie process when did exit parent process did not yet run waitpid
, wait
or waitid
on it. in normal situation parent want know exit status on child process spawned , therefore woud run waitpid on pid got fork
.
what happens in code above:
- the child spawned , exits (leaves else clause , returns 0)
- the parent runs endless
pause
loop until press ctrl-c (the sleep , waitpid superflous)
if start program , leave running (./a.out &
) , run ps -fx
see this:
6940 pts/1 sn 0:00 ./a.out 6943 pts/1 zn 0:00 \_ [a.out] <defunct>
now, if kill parent process (kill 6940
) child becomes orphan , init process automatically becomes new parent. since init process runs waitpid
(aka "reaps" child) on processes inherits zombie process deleted process table , not show more via ps -f
Comments
Post a Comment