c++ - 僵尸进程无法通过 waitpid 调用进行清理

标签 c++ unix fork parent-child waitpid

我正在使用 htop 观察进程,我发现即使我使用 waitpid 调用进行清理,子进程仍保持僵尸状态。知道为什么会发生这种情况吗?

非常感谢!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>

void child_signal_handler(int signal) {
  printf("Someone is stabbed me with signal %d\n", signal);
}

int main(int argc, char** argv)
{
  const pid_t child = fork();

  if (child == 0) {
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = &child_signal_handler;
    sigaction(SIGTERM, &sa, NULL);
    printf("Child is started in busy loop\n");
    while (true)
      ;
  } else {
    const int mercy_period = 3;
    printf("Parent is angry and gonna kill his child in %d sec\n", mercy_period);
    sleep(mercy_period);
    kill(child, SIGTERM);
    // clean-up zombie child process as it is terminated before we can wait on
    // it
    int status = 0;
    while(waitpid(-1, &status, WNOHANG) > 0);
  }

  return EXIT_SUCCESS;
}

最佳答案

waitpid glibc实现注释

If PID is (pid_t) -1, match any process. If the WNOHANG bit is set in OPTIONS, and that child is not already dead, return (pid_t) 0.

0 > 0 为 false 时,while 循环明显立即退出。

else和信号更改为SIGKILL

} else {
    const int mercy_period = 3;
    printf("Parent is angry and gonna kill his child in %d sec\n", mercy_period);
    sleep(mercy_period);
    kill(child, SIGKILL);
 
    int status = 0;
    pid_t pid = waitpid(-1, &status, WNOHANG);
    while(!pid) {
        pid = waitpid(-1, &status, WNOHANG);
        printf("%d\n", pid);    
    }
}

经过几次尝试后,waitpid 将返回子进程的 pid。成功了。

enter image description here

关于c++ - 僵尸进程无法通过 waitpid 调用进行清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63370473/

相关文章:

c++ - 'class std::map<std::basic_string<char>, Gui >' has no member named ' emplace'

linux - 将值从一个 shell 脚本传递到另一个 shell 脚本

c - C 语言 shell 、输入和管道

c++ - OpenCV 试图将两个不同的图像合二为一

长序列上的 C++ 正则表达式段错误

unix - GPG仅在内存中解密/加密字符串

unix - sed 仅在第一行匹配后插入?

c - kill会被一个信号打断吗?

c - 当我从 c 中的 fork 子执行 exec() 时会发生什么

c++ - 是否可以在函数中使用#define?