如何避免僵尸进程?以及在这种情况下init进程究竟做了什么?

时间:2016-11-17 19:12:44

标签: process operating-system zombie-process

如何避免僵尸进程?以及在这种情况下init进程究竟做了什么?
我见过这个程序,但无法得到它:  该程序如何创建僵尸进程:

#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 the child already had ended. */
        sleep(1); /* Wait 1 seconds for the child to end. And eat away the SIGCHLD in case if arrived. */
        pause(); /* Suspend main task. */
    }
    else
    {
        sleep(3); /* Just let the child live for some tme before becoming a zombie. */
    }

    return 0;
}

1 个答案:

答案 0 :(得分:0)

子进程在退出时变为僵尸进程,但父进程尚未运行waitpidwaitwaitid。在正常情况下,父母会想知道它产生的子进程的退出状态,因此在fork获得的pid上运行waitpid

上面的代码会发生什么:

  • 生成并退出子项(离开else子句并返回0)
  • 父进入无限pause循环,直到你按ctrl-c(睡眠和waitpid是超级的)

如果您启动该程序并让其继续运行(./a.out &),然后运行ps -fx,那么您会看到如下内容:

 6940 pts/1    SN     0:00      ./a.out
 6943 pts/1    ZN     0:00       \_ [a.out] <defunct>

现在,如果您终止父进程(kill 6940),则子进程成为孤儿,init进程自动成为新进程。由于init进程在所有进程上运行waitpid(又名&#34; reaps&#34;子进程),它继承了僵尸进程,最终从进程表中删除,并且不会再通过{{1}显示}

相关问题