while(wait(NULL)> 0)对结果的怀疑 [英] while(wait(NULL) > 0) doubts with result

查看:58
本文介绍了while(wait(NULL)> 0)对结果的怀疑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,我必须解释出口处发生的情况.

I have a piece of code and I have to explain what is happening in the exit.

while(wait(NULL)>0)

代码如下:

#include <stdio.h>
 main() {
   int n=1;
   while(n<5) {
   n=n+1;   
     if (fork() == 0) 
       n=n+2;
   }
   printf("%d %d %d\n", getpid(), getppid(), n);
   while (wait(NULL) > 0);
 }

当我执行程序时,结果显示6个进程,其中有6个孩子和各自的父母,而条件而n <已达到5 .如果我们取消

When I execute the program the result shows 6 processes with 6 children and respective parents, while the condition while n < 5 has been met. If we cancel

while (wait(NULL) > 0);

然后一些孩子仍然是僵尸.

then some children remain as zombies.

例如,当您在第一个孩子中时,输出应为n = 4而不是n = 5并随机输出结果而无顺序.

For example, when you are in the first child the output should be n = 4 instead I get n = 5 and outputs the results randomly without order.

我想准确了解 while(wait(NULL)> 0)

推荐答案

如果当前进程没有子进程,则 wait(NULL)返回-1.否则,它将等待直到其中一个退出,然后返回其进程ID.

If the current process have no child processes, wait(NULL) returns -1. Otherwise it waits until one of them exits, and returns it's process ID.

因此,当 wait(NULL)>0); 循环直到没有更多的子进程为止,因为当最后一个子进程退出时,wait()将返回-1,而while循环终止.(并且wait()返回0也是不可能的条件.)

So while wait(NULL) > 0); loops until there are no more child processes, since when the last child exits, wait() will return -1 and the while loop terminates. (And wait() returning 0 should be an impossible condition too).

这篇关于while(wait(NULL)&gt; 0)对结果的怀疑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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