【问题标题】:How to create Zombie Process?如何创建僵尸进程?
【发布时间】:2016-04-13 01:31:16
【问题描述】:

我正在编写程序来创建僵尸进程(出于学习目的)。

int main(int argc, char *argv[]) {

  int i = ::fork();

  if(i == 0) sleep(30);
  else printf("process %d/%d\n", getpid(), i); 

  return 0;

}

上面的代码在子进程上调用fork而没有waitpid。但是,在启动此代码后,我使用ps aux | grep 'Z' 试图找到僵尸进程。我什么也没看到。子进程出现在进程列表中,30 秒后 (sleep) 它消失了,我在进程列表中找不到状态为 'Z' 的任何内容。这段代码真的会创建一个僵尸进程吗?

【问题讨论】:

  • 你还没有创造一个僵尸,你创造了一个孤儿。
  • 在这种情况下如何创建僵尸?
  • 所以,如果父母比孩子先死,孩子就会成为孤儿(很明显)。如果孩子在父母之前死去,孩子就会变成僵尸,直到父母为它wait()s。
  • 好吧,我将sleep(30) 移到了else 块中,这样在没有wait 的情况下,父级一个接一个地死去。但我再次使用ps aux | grep 'Z' 并没有找到任何具有僵尸状态的进程。可能是什么原因?
  • 首先,这实际上是c++,而不是c。其次,一旦父母去世,它拥有的所有孩子(孤儿和僵尸孤儿)都将成为该州的监护人(重新成为init/pid one)。 init 等待它的所有孩子。

标签: c process fork zombie-process


【解决方案1】:
int main(int argc, char *argv[])
{
    int i = fork();

    if(i == 0)
    {
        exit(0); /* we let the child die as fast as possible */
    } else {
        printf("process %d/%d\n", getpid(), i);
        sleep(30); /* during these 30 sec, the child is a zombie, because it is dead, but not reaped with waitpid yet. Use ps command during this to see it in the process list */
    }
    /* when we do not reap the child before we exit, it will either be removed by OS or reaped by init as it is reparented */
    return 0;
}

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 2016-12-13
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    相关资源
    最近更新 更多