c - 僵尸进程的父进程终止后会发生什么?

标签 c linux zombie-process

我很好奇,如果僵尸进程的父进程不关心等待它会发生什么。

假设,我们有一个 parent 和一个 child 。 child 在 parent 之前终止。

来自 APUE:

The kernel keeps a small amount of information for every terminating process...Minimally
this information consists of the process ID, the termination status of the process....

家长需要使用 waitpid() 获取此信息。
但是,如果 parent 没有等待 child 就退出了,会发生什么:

内核是否删除了这些信息(肯定没用)?
或者,它一直在收集这些垃圾?
这个实现具体吗?
或者,是否有处理这种情况的标准方法?

最佳答案

init 会自动采用孤儿进程,它有一个标准的 SIGCHLD 处理程序,它只会丢弃死进程的任何退出状态。

在您的情况下,如果僵尸进程的父进程死亡,僵尸孤儿将被 init 收养并清理。

下面的代码对此进行了测试:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>


int main() {
    pid_t child_pid;
    if (child_pid = fork()) { // fork a child, child will exit straight away
        char name[128];
        sprintf(name, "/proc/%d/stat", child_pid);
        char line[2048];

        // read childs /proc/pid/stat, field 3 will give its status
        FILE * fp = fopen(name, "r");

        while (fgets(line, sizeof(line), fp))
            puts(line);

        fclose(fp);

        usleep(5000000);

        // by now the child will have exited for sure, repeat
        fp = fopen(name, "r");

        while (fgets(line, sizeof(line), fp))
            puts(line);

        fclose(fp);

        // make another child to repeat the process and exit the parent
        if (!fork()) {
            usleep(5000000);
            // both parent and child will have exited by now

            fp = fopen(name, "r");

            // this should fail because init has already cleaned up the child
            if (!fp) {
                perror("fopen");
                return -1;
            }

            while (fgets(line, sizeof(line), fp))
                puts(line);

            fclose(fp);
        }

    }

    return 0;
}

关于c - 僵尸进程的父进程终止后会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17236630/

相关文章:

python - 僵尸状态多处理库python3

c - 何时使用 union ,何时使用结构

c - Arduino EEPROM 似乎不稳定,我应该写两次吗?

linux - 检查命令是否在 bashrc 中运行

linux - 如何让服务知道当前用户名

Linux僵尸进程Xsession

c - 将随机索引选取到排序数组中

cygwin make - 对 INT_MAX 和 argp_usage 的 undefined reference

linux - 如何在unix中转置或旋转文本文件的数据?

ios - Xcode 5 Instruments 不显示僵尸