我只是好奇,如果僵尸进程的父进程不关心等待它,会发生什么。
假设,我们有一个父母和一个孩子。子进程先于父进程终止。
来自APUE:
内核为每个终止进程保留少量信息......最少
该信息包括进程 ID、进程的终止状态......
家长需要使用以下方式获取此信息waitpid()
.
但是,如果父进程不等待子进程就退出,会发生什么:
内核是否删除了这些信息(当然没有用)?
或者,它一直在收集这些垃圾?
这个实现具体吗?
或者,有没有标准的方法来处理这种情况?
孤儿进程自动被采用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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)