维基百科说“终止但从未被其父进程等待的子进程成为僵尸进程。”我运行这个程序:
#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
....
.....
但为什么在这种情况下“子进程终止但未被其父进程等待”?
最佳答案
在您的代码中,zombie 是在 exit(0)
上创建的(下面有箭头的评论):
pid=fork();
if (pid==0) {
exit(0); // <--- zombie is created on here
} else {
// some parent code ...
}
为什么?因为你从不wait
编辑它。当有人调用 waitpid(pid)
,它返回有关进程的事后分析信息,例如它的退出代码。不幸的是,当进程退出时,内核不能直接处理这个进程入口,否则返回码将丢失。所以它等待某人wait
在它上面,并保留这个进程条目,即使它除了进程表中的条目之外并没有真正占用任何内存——这正是所谓的僵尸。
避免创建僵尸的选项很少:
添加
waitpid()
父进程中的某处。例如,这样做将有助于:pid=fork(); if (pid==0) { exit(0); } else { waitpid(pid); // <--- this call reaps zombie // some parent code ... }
执行双重
fork()
在孙子还活着的时候获得孙子并退出子代。init
将自动收养孙辈如果他们的 parent (我们的 child )去世,这意味着如果孙子去世,它将自动wait
由init
编辑.换句话说,您需要执行以下操作:pid=fork(); if (pid==0) { // child if (fork()==0) { // grandchild sleep(1); // sleep a bit to let child die first exit(0); // grandchild exits, no zombie (adopted by init) } exit(0); // child dies first } else { waitpid(pid); // still need to wait on child to avoid it zombified // some parent code ... }
明确忽略父级中的 SIGCHLD 信号。当 child 去世时, parent 会被送去
SIGCHLD
让它对 child 死亡使用react的信号。您可以调用waitpid()
收到此信号后,或者您可以安装显式忽略信号处理程序(使用signal()
或sigaction()
),这将确保 child 不会变成僵尸。换句话说,像这样:signal(SIGCHLD, SIG_IGN); // <-- ignore child fate, don't let it become zombie pid=fork(); if (pid==0) { exit(0); // <--- zombie should NOT be created here } else { // some parent code ... }
关于linux - 为什么会存在僵尸进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16078985/