创建僵尸进程 [英] Create zombie process

查看:121
本文介绍了创建僵尸进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对创建僵尸进程感兴趣.据我了解,僵尸进程发生在父进程在子进程之前退出时.但是,我尝试使用以下代码重新创建僵尸进程:

I am interested in creating a zombie process. To my understanding, zombie process happens when the parent process exits before the children process. However, I tried to recreate the zombie process using the following code:

#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main ()
{
  pid_t child_pid;

  child_pid = fork ();
  if (child_pid > 0) {
    exit(0);
  }
  else {
    sleep(100);
    exit (0);
  }
  return 0;
}

但是,此代码将在执行后立即退出,这是预期的.但是,像我一样

However, this code exits right after execute which is expected. However, as I do

ps aux | grep a.out

我发现a.out只是作为正常进程运行,而不是我期望的僵尸进程.

I found a.out is just running as a normal process, rather than a zombie process as I expected.

我正在使用的操作系统是ubuntu 14.04 64位

The OS I am using is ubuntu 14.04 64 bit

推荐答案

报价:

据我所知,僵尸进程发生在父进程在子进程之前退出的时候.

To my understanding, zombie process happens when the parent process exits before the children process.

这是错误的.根据 man 2 wait (请参见注释):

This is wrong. According to man 2 wait (see NOTES) :

终止但尚未等待的孩子变成了僵尸".

A child that terminates, but has not been waited for becomes a "zombie".

因此,如果要创建一个僵尸进程,在fork(2)之后,子进程应为exit(),父进程应为sleep(),然后再退出,这使您有时间观察ps(1).

So, if you want to create a zombie process, after the fork(2), the child-process should exit(), and the parent-process should sleep() before exiting, giving you time to observe the output of ps(1).

例如,您可以使用下面的代码代替您的代码,并在sleep() ing时使用ps(1):

For instance, you can use the code below instead of yours, and use ps(1) while sleep()ing:

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

int main(void)
{
    pid_t pid;
    int status;

    if ((pid = fork()) < 0) {
        perror("fork");
        exit(1);
    }

    /* Child */
    if (pid == 0)
        exit(0);

    /* Parent
     * Gives you time to observe the zombie using ps(1) ... */
    sleep(100);

    /* ... and after that, parent wait(2)s its child's
     * exit status, and prints a relevant message. */
    pid = wait(&status);
    if (WIFEXITED(status))
        fprintf(stderr, "\n\t[%d]\tProcess %d exited with status %d.\n",
                (int) getpid(), pid, WEXITSTATUS(status));

    return 0;
}

这篇关于创建僵尸进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆