创build僵尸进程

我有兴趣创build一个僵尸进程。 据我的理解,僵尸进程发生在父进程退出之前的subprocess。 不过,我尝试使用下面的代码重新创build僵尸进程:

#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位

引用:

 To my understanding, zombie process happens when the parent process exits before the children process. 

这是错误的。 根据man 2 wait (见注):

 A child that terminates, but has not been waited for becomes a "zombie". 

所以,如果你想创建一个僵尸进程,在fork(2) ,子进程应该exit() ,并且父进程应该在退出之前sleep() ,给你时间来观察ps(1)

例如,您可以使用下面的代码而不是您的代码,并在sleep() ing时使用ps(1)

 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(void) { pid_t pid; int status; if ((pid = fork()) < 0) { perror("fork"); exit(1); } /* Child */ if (pid == 0) exit(0); /* Parent * Gives you time to observe the zombie using ps(1) ... */ sleep(100); /* ... and after that, parent wait(2)s its child's * exit status, and prints a relevant message. */ pid = wait(&status); if (WIFEXITED(status)) fprintf(stderr, "\n\t[%d]\tProcess %d exited with status %d.\n", (int) getpid(), pid, WEXITSTATUS(status)); return 0; }