我想弄清楚为什么这条语句会产生 2 个进程
if(fork()&&(fork()||fork()))
printf("Hello");
我了解短路问题,而且我知道如果不使用 if 执行此语句,我们将总共获得 4 个进程。那么你能解释一下通过在这样的语句中插入 if 来使用的标准吗?
最佳答案
应该创建了 4 个进程。您可以通过在 if
语句之后放置一个额外的 printf
调用来轻松验证这一点。
printf("Hello")
只运行了两次,因为只有其中两个进程的条件为真。
具体来说,根进程产生了两个子进程,第二个子进程又产生了一个:
<parent> : condition is true because the two first fork calls return non-0 : (true && (true || ??))
<child1> : condition is false because the first fork returns 0: (false && (?? || ??))
<child2> : condition is true because the first and third fork calls return non-0: (true && (false || true))
<child3> : condition is false because the second and third fork calls return 0: (true && (false || false))
关于c - 为什么进程总数是2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28299306/