涉及fork()的C程序输出的说明 [英] Explanation of a output of a C program involving fork()
问题描述
运行该程序将打印"forked!". 7次.有人可以解释如何分叉!"被打印了7次?
Running this program is printing "forked!" 7 times. Can someone explain how "forked!" is being printed 7 times?
#include<stdio.h>
#include<unistd.h>
int main(){
fork() && fork() || fork() && fork();
printf("forked!\n");
return 0;
}
推荐答案
这里使用了几个概念,第一个概念是知道fork
的作用以及在某些情况下返回的结果.不久,当它被调用时,它将创建调用方的重复进程,并在子进程中返回0
(对于逻辑表达式,为false
),对于父进程,返回非零(对于逻辑表达式,为true
).
实际上,如果发生错误,它可能会返回一个负(非零)值,但是在此我们假定它总是成功.
There're several concepts being used here, first one is knowing what fork
does and what it returns in certain circumstances. Shortly, when it gets called, it creates a duplicate process of the caller and returns 0
(false
for logical expressions) in child process and non-zero (true
for logical expressions) for parent process.
Actually, it could return a negative (non-zero) value in case of an error, but here we assume that it always succeeds.
第二个概念是对逻辑表达式(例如&&
和||
)的短路计算,特别是0 && fork()
将 not 调用fork()
,因为如果第一个操作数是false
(零),则无需计算第二个.同样,1 || fork()
也不会调用fork()
.
The second concept is short-circuit computation of logical expressions, such as &&
and ||
, specifically, 0 && fork()
will not call fork()
, because if the first operand is false
(zero), then there's no need to compute the second one. Similarly, 1 || fork()
will not call fork()
neither.
还要注意,在子进程中,表达式的计算在与父进程相同的地方继续进行.
Also note that in child processes the computation of the expression continues at the same point as in the parent process.
此外,请注意,由于优先级高,因此按以下顺序计算表达式:
Also, note that the expression is computed in the following order due to precedence:
(fork() && fork()) || (fork() && fork())
这些观察结果将引导您找到正确的答案.
These observations should lead you to the correct answer.
考虑fork() && fork()
fork()
/ \
false true && fork()
/ \
false true
因此,这里我们创建了三个进程,其中两个返回结果为false
,另一个返回true
.然后,对于||
,我们让所有返回false
的进程试图再次运行同一条语句,因此我们将2 * 3 + 1 = 7
作为答案.
So here we have three processes created, two of which return false
as the result and one returning true
. Then for ||
we have all the processes returning false
trying to run the same statement again, so we have 2 * 3 + 1 = 7
as the answer.
这篇关于涉及fork()的C程序输出的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!