如何创建Zombie Process?

时间:2016-04-13 01:31:16

标签: c process fork zombie-process

我正在编写程序来创建僵尸进程(用于学习目的)。

int main(int argc, char *argv[]) {

  int i = ::fork();

  if(i == 0) sleep(30);
  else printf("process %d/%d\n", getpid(), i); 

  return 0;

}

以上代码在子进程上调用fork而没有waitpid。但是,在启动此代码后,我使用ps aux | grep 'Z'尝试查找僵尸进程。我没有看到任何东西。子进程出现在进程列表中,30秒后不久(sleep)它就消失了,我在进程列表中找不到任何状态为'Z'的进程。这段代码是否真的会创建一个僵尸进程?

1 个答案:

答案 0 :(得分:2)

int main(int argc, char *argv[])
{
    int i = fork();

    if(i == 0)
    {
        exit(0); /* we let the child die as fast as possible */
    } else {
        printf("process %d/%d\n", getpid(), i);
        sleep(30); /* during these 30 sec, the child is a zombie, because it is dead, but not reaped with waitpid yet. Use ps command during this to see it in the process list */
    }
    /* when we do not reap the child before we exit, it will either be removed by OS or reaped by init as it is reparented */
    return 0;
}