分叉进程:在子进程终止时恢复父进程 (Linux)

Fork process: Resume parent process while children terminated (Linux)

我编写了一个 C++ 应用程序,它等待事件发生(例如等待传入连接)。在该事件发生后,它将通过派生一个处理该事件的子进程来继续。

所以,我的代码基本上是这样的:

int main(void) {
  while(1) {
    Event e = waitUntilSomethingHappens(); // blocks execution until event occurs
    pid_t pid = fork(); 
    if (pid == 0) {
      doChildStuff(e); 
      exit(0); 
      return 0; 
    }
  }
  return 0;
}

我现在的期望是子进程将终止(因为 exit(0) and/or return)。确实,它离开了 while 循环,但它似乎并没有终止。当我点击 ps -e 时,两个进程都会显示,而子进程被标记为 <defunct>

为什么它没有消失?我该怎么做才能让它消失?

您必须使用 wait calls 之一来获取 child 状态更改的通知。

来自手册:

A child that terminates, but has not been waited for becomes a "zombie". The kernel maintains a minimal set of information about the zombie process (PID, termination status, resource usage information) in order to allow the parent to later perform a wait to obtain information about the child. As long as a zombie is not removed from the system via a wait, it will consume a slot in the kernel process table, and if this table fills, it will not be possible to create further processes. If a parent process terminates, then its "zombie" children (if any) are adopted by init(8), which automatically performs a wait to remove the zombies.