简体   繁体   English

僵尸进程未通过 waitpid 调用进行清理

[英]Zombie process is not cleanup with waitpid call

I am watching the processes with htop and I see that child process stays as zombie even though I clean up with waitpid call.我正在用 htop 观察进程,我看到即使我用 waitpid 调用进行清理,子进程仍保持为僵尸状态。 Any idea why this might happen?知道为什么会发生这种情况吗?

Thank you very much!非常感谢!

#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 implementation comments waitpid glibc 实现注释

If PID is (pid_t) -1, match any process.如果 PID 为 (pid_t) -1,则匹配任何进程。 If the WNOHANG bit is set in OPTIONS, and that child is not already dead, return (pid_t) 0.如果在 OPTIONS 中设置了 WNOHANG 位,并且该孩子尚未死亡,则返回 (pid_t) 0。

The while loop clearly exits immediately as 0 > 0 is false.0 > 0为假时,while 循环显然会立即退出。

Change the else and the signal to SIGKILLelse和信号更改为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);    
    }
}

After few attempts waitpid will return the pid of the child process.经过几次尝试后, waitpid将返回子进程的 pid。 A success.成功。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM