【发布时间】:2014-09-30 02:22:55
【问题描述】:
我有兴趣创建一个僵尸进程。据我了解,僵尸进程发生在父进程在子进程之前退出时。但是,我尝试使用以下代码重新创建僵尸进程:
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t child_pid;
child_pid = fork ();
if (child_pid > 0) {
exit(0);
}
else {
sleep(100);
exit (0);
}
return 0;
}
但是,此代码在预期执行后立即退出。但是,和我一样
ps aux | grep a.out
我发现 a.out 只是作为正常进程运行,而不是我预期的僵尸进程。
我使用的操作系统是 ubuntu 14.04 64 位
【问题讨论】:
-
您问题中的代码不会创建僵尸进程,因为在您的代码中,父进程首先退出,而子进程继续运行。 (请记住,fork() 在子进程中返回 0,在父进程中返回子进程的 PID。)要查看僵尸进程,您需要在父进程还活着但没有等待子进程时让子进程退出。如果您只是将代码的第 10 行从
if (child_pid > 0)更改为if (child_pid == 0),它将“修复”您的代码,并且当子进程退出时您将能够看到僵尸进程。
标签: c linux operating-system fork zombie-process