簡體   English   中英

僵屍進程未通過 waitpid 調用進行清理

[英]Zombie process is not cleanup with waitpid call

我正在用 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 實現注釋

如果 PID 為 (pid_t) -1,則匹配任何進程。 如果在 OPTIONS 中設置了 WNOHANG 位,並且該孩子尚未死亡,則返回 (pid_t) 0。

0 > 0為假時,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。 成功。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM