【发布时间】:2013-04-11 08:00:31
【问题描述】:
维基百科说“一个终止但从未被其父进程等待的子进程成为僵尸进程。”我运行这个程序:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid, ppid;
printf("Hello World1\n");
pid=fork();
if(pid==0)
{
exit(0);
}
else
{
while(1)
{
printf("I am the parent\n");
printf("The PID of parent is %d\n",getpid());
printf("The PID of parent of parent is %d\n",getppid());
sleep(2);
}
}
}
这会创建一个僵尸进程,但是我不明白为什么这里会创建一个僵尸进程?
程序的输出是
Hello World1
I am the parent
The PID of parent is 3267
The PID of parent of parent is 2456
I am the parent
The PID of parent is 3267
The PID of parent of parent is 2456
I am the parent
....
.....
但是为什么在这种情况下“子进程终止但没有被其父进程等待”?
【问题讨论】:
-
你是在问为什么在 Unix 中引入了僵尸进程的概念?就目前而言,我看到的对您的问题的唯一答案是“因为僵尸进程就是这样定义的”。
-
“无法理解为什么会在此处创建僵尸进程” 那是因为您没有调用
wait()来读取子进程的退出状态,从而读取它的条目留在进程表中。 -
没关系。但是当孩子跑了一段时间并且存在时,没有任何僵尸
-
是的——僵尸是活死人。僵尸进程已经死亡(由于信号或因为它们退出),并且父进程尚未为该进程执行
wait()。僵尸已经死了,但仍然占据一个进程表槽,并且会继续这样做,直到它的父进程等待它,或者父进程退出。如果父进程退出,子进程将被init进程(通常是PID 1)继承,而该进程的主要目的之一(如果不是唯一的)就是等待子进程死亡。 -
子进程执行
exit(0);,从而终止。父进程无需等待子进程死亡就进入无限循环。在这种情况下,等待意味着“调用函数wait()或waitpid()之一,或各种依赖于系统的替代方法之一,例如wait3()或wait4()”。这不仅仅意味着“父母继续生活”。当孩子没有死的时候,就没有僵尸进程的可能;僵尸进程已死。
标签: linux unix process fork zombie-process