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

mgu*_*gus 5 c pid process 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;
}
Run Code Online (Sandbox Code Playgroud)

因此,父进程调用子进程的waitpid,如果子进程尚未退出,则立即返回.所以,到目前为止,没有僵尸可以出现.但是,如果孩子退出之前

return 0;
命令这将是一个僵尸呢?我其实很困惑.在程序终止之前,waitpid应该是最后一行代码吗?任何帮助,将不胜感激.谢谢!

alk*_*alk 6

如果孩子结束,孩子只会变成僵尸,而父母wait*() 只要自己活着就不会打电话.

在父母也结束的那一刻,孩子被init过程收割,这个过程会照顾wait*()孩子,所以它最终会结束,并且离开僵尸状态并从过程列表中消失.

要激活在您的示例代码中创建的子代变为僵尸修改代码,例如如下:

#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;
}
Run Code Online (Sandbox Code Playgroud)

由于以下两个事实:

  • 孩子睡了3s,所以父母的呼叫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;
}
Run Code Online (Sandbox Code Playgroud)