linux - 为什么会存在僵尸进程?

标签 linux unix process fork zombie-process

维基百科说“终止但从未被其父进程等待的子进程成为僵尸进程。”我运行这个程序:

#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 am the parent\n");
        printf("The PID of parent is %d\n",getpid());
        printf("The PID of parent of parent is %d\n",getppid());        
        sleep(2);
        }
    }
}

这就创建了一个僵尸进程,但是我不明白为什么要在这里创建一个僵尸进程?

程序的输出是

Hello World1
I am the parent
The PID of parent is 3267
The PID of parent of parent is 2456
I am the parent
The PID of parent is 3267
The PID of parent of parent is 2456
I am the parent
....
.....

但为什么在这种情况下“子进程终止但未被其父进程等待”?

最佳答案

在您的代码中,zombie 是在 exit(0) 上创建的(下面有箭头的评论):

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

为什么?因为你从不wait编辑它。当有人调用 waitpid(pid) ,它返回有关进程的事后分析信息,例如它的退出代码。不幸的是,当进程退出时,内核不能直接处理这个进程入口,否则返回码将丢失。所以它等待某人wait在它上面,并保留这个进程条目,即使它除了进程表中的条目之外并没有真正占用任何内存——这正是所谓的僵尸

避免创建僵尸的选项很少:

  1. 添加waitpid()父进程中的某处。例如,这样做将有助于:

    pid=fork();
    if (pid==0) {
        exit(0);    
    } else {
        waitpid(pid);  // <--- this call reaps zombie
        // some parent code ...
    }
    
  2. 执行双重 fork() 在孙子还活着的时候获得孙子并退出子代。 init 将自动收养孙辈如果他们的 parent (我们的 child )去世,这意味着如果孙子去世,它将自动waitinit 编辑.换句话说,您需要执行以下操作:

    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. 明确忽略父级中的 SIGCHLD 信号。当 child 去世时, parent 会被送去SIGCHLD让它对 child 死亡使用react的信号。您可以调用waitpid()收到此信号后,或者您可以安装显式忽略信号处理程序(使用 signal()sigaction() ),这将确保 child 不会变成僵尸。换句话说,像这样:

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

关于linux - 为什么会存在僵尸进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16078985/

相关文章:

bash - 使用 Bash 时需要转义哪些字符?

无法使用 open() 系统调用打开第二个文件

c - C语言进程同步

php - 管理持久 PHP 脚本进程的推荐方法?

linux - 使用 crosstool-ng 构建 ARM 交叉编译器失败

linux - Bash 中的流量控制是什么?

linux - Linux 头文件中的 asm 与 asm-generic —— 它们相同吗

python - 如何在运行时安装和导入 Python 模块?

c++ - 在 Unix 上使用 C++ 的正则表达式

windows - 如何休眠应用程序?