exit(0) 和僵尸进程有什么关系

what's the relationship between exit(0) and zombie process

我发现当我从子部分中删除 exit(0); 时,它无法创建僵尸进程。你能告诉我为什么吗?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

int main() {
      if(!fork()) {
        printf("child pid=%d\n", getpid());
        exit(0);
      }

      sleep(20);

      printf("parent pid=%d\n",getpid());
      exit(0);
}

僵尸进程是 parent 进程尚未检查的死 child 进程。原代码中,child比parent提前20秒结束,所以是20秒的僵尸。如果您删除第一个 exit(0),它们都会存活 20 秒,因为在 child 中,控制会直接从 if 块的底部传递出去,除非有什么东西阻止它。

因此,如果您删除 child 的 exit(),那么它不仅不太可能在可观察的时间内变成僵尸,而且您应该会看到它打印 "parent pid" 消息以及 "child pid" 消息。