这段 C 代码可以创建僵尸进程吗?

标签 c process pid zombie-process waitpid

我想知道下面的代码是否可以创建僵尸:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(){
    int i=1;
    pid_t p;
    p = fork();
    i++;
    if(p!=0){
        waitpid(p, NULL, 0);
    }
    printf("%d\n",i);
    return 0;
}

因此,父进程为子进程调用 waitpid,如果子进程尚未退出,则它会立即返回。所以,到目前为止还没有僵尸出现。但是,如果 child 在

return 0;
之前退出命令这会是一个僵尸吗?我实际上对此感到困惑。 waitpid 应该是程序终止前的最后一行代码吗?任何帮助,将不胜感激。谢谢!

最佳答案

只有当它结束并且 parent 不调用wait*() 只要它自己继续存在时, child 才会变成僵尸.

在 parent 也结束的那一刻, child 被 init 进程收割,该进程将注意调用 child 的 wait*(),所以它最终会结束并由此离开僵尸状态并从进程列表中消失。

要激怒在您的示例代码中创建的 child 成为僵尸修改代码示例如下:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void) 
{
    pid_t p = fork();

    if (p != 0) 
    {
        waitpid(p, NULL, 0); /* See if the child already had ended. */
        sleep(1); /* Wait 1 seconds for the child to end. And eat away the SIGCHLD in case if arrived. */
        pause(); /* Suspend main task. */
    }
    else
    {
        sleep(3); /* Just let the child live for some tme before becoming a zombie. */
    }

    return 0;
}

由于以下两个事实:

  • child 睡了 3 秒,所以 parent 对 waitpid() 的调用很可能总是失败
  • SIGCHLD 的默认处理是忽略它。

上面的代码实际上是一样的:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void) 
{
    pid_t p = fork();

    if (p != 0) 
    {
        pause(); /* Suspend main task. */
    }
    else
    {
        sleep(3); /* Just let the child live for some tme before becoming a zombie. */
    }

    return 0;
}

关于这段 C 代码可以创建僵尸进程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20598815/

相关文章:

c - 如何读取不确定大小的 C 字符数组?

c - 将毫秒添加到 C 日期

c - float 一个( float );意义?

java - 使用类路径 (cp) 在单独的位置执行 java 控制台应用程序

c++ - 使用 stringstream 将 pid_t 转换为 const char*

linux - 在 Linux 中创建子进程

c - 我如何以编程方式生成类似/proc/pid/maps 的东西?

Node.JS 父进程 ID

javascript - Node.js 从 0.10.2 更新到 0.12.2 后出现错误 "ReferenceError: global is not defined"

c# - 如何通过 PID 向 CMD 进程发送关闭命令