我想知道下面的代码是否可以创建僵尸:
#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/