僵尸进程的父进程终止后会发生什么? [英] What happens after the parent of zombie process terminates?

查看:249
本文介绍了僵尸进程的父进程终止后会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,僵尸进程会发生什么,如果它的父母不在乎等待它的话.

I'm just curious, what happens to zombie process, if it's parent doesn't care to wait for it.

假设我们有一个父母和一个孩子.孩子先于父母终止.

Suppose, we've a parent and a child. Child terminates before parent does.

从APUE:

内核为每个终止进程保留少量信息...至少
此信息包括进程ID,进程的终止状态....

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 is required to fetch this information using waitpid().
But if, parent exits without waiting for child, what happens:

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

Does the kernel delete this information (certainly it's of no use)?
Or, it keeps collecting this junk?
Is this implementation specific?
Or, is there a standard way to deal with this situation?

推荐答案

init自动采用孤立进程,该进程具有标准的SIGCHLD处理程序,该处理程序仅丢弃无效进程的退出状态.

Orphan processes are automatically adopted by init which has a standard SIGCHLD handler that just discards any exit status of a dead process.

在您的情况下,如果僵尸进程的父进程死亡,则僵尸孤儿将被init接受并清理.

In your case if the parent of a zombie process dies the zombie orphan will be adopted by init and cleaned up.

以下代码对此进行了测试:

The following code tests this:

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

这篇关于僵尸进程的父进程终止后会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆