c++ - 如何创建几分钟无法收割的僵尸进程

标签 c++ c linux zombie-process

有人可以建议我一种简单的方法来创建一个几分钟内无法收获的僵尸进程吗? 这样做的目的是测试父进程是否能够在僵尸进程再次可获取后获取它们。

可以找到一个不可收割僵尸的案例 here 。我想可能有更简单的方法来做到这一点。

操作系统:Linux

首选语言:C/C++

最佳答案

这里有一个小程序,它会导致僵尸在“ps aux”输出中出现几分钟。注意注释掉的 waitpid() 调用;如果您取消对该调用的注释,僵尸进程将不会出现,因为 waitpid() 调用会导致父进程声明其已死亡的子进程。

(免责声明:我只在 MacOS/X 下测试过这个,因为那是我所在的计算机,但它在 Linux 下应该同样工作)

#include <stdio.h>
#include <signal.h>
#include <pthread.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
   printf("Starting Program!\n");

   int pid = fork();
   if (pid == 0)
   {
      printf("Child process %i is running!\n", getpid());
      sleep(300);  // wait 5 minutes
      printf("Child process %i is exiting!\n", getpid());
      return 0;
   }
   else if (pid > 0)
   {
      printf("Parent process is continuing child's pid is %i...\n", pid);
      sleep(5);  // just for clarity
      printf("Parent process is sending SIGKILL to child process...\n");
      if (kill(pid, SIGKILL) != 0) perror("kill");
      // waitpid(pid, NULL, 0);  // uncomment this to avoid zombie child process

      printf("Parent process is sleeping... ps aux should show process #%i is a zombie now\n", pid);
      sleep(500);  // just for clarity
      printf("Parent process is exiting!\n");
   }
   else perror("fork()");
}

关于c++ - 如何创建几分钟无法收割的僵尸进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705907/

相关文章:

c++ - 访问特征矩阵的行 vector 时复制或引用

C蛇游戏与自身相撞

c - 如何在 C 中的动态双指针中存储一行

mysql - 将查询存储在bash中的数组中

php - file_exists/www/web/app/aaa/../../bbb.php 返回false,报open_basedir限制错误

c++ - 如何在不复制此代码的情况下将一些代码放入多个命名空间?

python - 使用 Swig 在成员中使用互斥锁包装 C++ 类时出现问题

c - 我应该在销毁它之前隐藏一个小部件吗?

linux - GNU make 中的复杂模式替换

c++ - const 参数不够 const