我只是好奇,如果它的父进程不想等待它,僵尸进程会发生什么。
假设,我们有一个父母和一个孩子。孩子在父母之前终止。
来自 APUE:
内核为每个终止进程保留少量信息......
这些信息至少包括进程ID,进程的终止状态......
家长需要使用 获取此信息waitpid()
。
但是,如果父母没有等待孩子就退出了,会发生什么:
内核是否删除了这些信息(肯定没用)?
或者,它一直在收集这些垃圾?
这个实现是特定的吗?
或者,是否有处理这种情况的标准方法?
我只是好奇,如果它的父进程不想等待它,僵尸进程会发生什么。
假设,我们有一个父母和一个孩子。孩子在父母之前终止。
来自 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;
}