【问题标题】:What happens after the parent of zombie process terminates?僵尸进程的父进程终止后会发生什么?
【发布时间】:2013-06-18 16:00:21
【问题描述】:

我只是好奇,如果它的父进程不想等待它,僵尸进程会发生什么。

假设,我们有一个父母和一个孩子。孩子在父母之前终止。

来自 APUE:

内核为每个终止进程保留少量信息...最少
该信息包括进程ID、进程的终止状态......

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

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

【问题讨论】:

  • init process 成为子进程的父进程,从进程表初始化刷新条目

标签: c linux zombie-process


【解决方案1】:

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;
}

【讨论】:

  • 既然child已经终止了,还会产生SIGCHLD信号吗?我认为它是在孩子终止时生成的(如果我错了,请纠正我)。
  • @mohit 好问题,可能不是。不能说,因为我知道没有办法在用户进程中采用进程。无论哪种方式init 都会清理孩子丢弃它的退出状态。引入 init 的整个采用是为了确保孤儿僵尸不会留在系统中。
  • +1,用于程序。它真的解释了,会发生什么。但是,我对如何实现这一点很感兴趣。如果这是特定于实现的,或者是否有标准方法。
  • @mohit 这是 Unix 和类 Unix 标准。大约SIGCHLD - init 会定期等待所有的孩子在必要时清理它们。来自:en.wikipedia.org/wiki/Zombie_process
猜你喜欢
  • 1970-01-01
  • 2013-04-11
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 2016-03-31
  • 1970-01-01
相关资源
最近更新 更多