我不明白叉的这个例子中() [英] I don't understand this example of fork()
问题描述
我有code的这个例子,但我不明白为什么code创建5流程加上原来的。 (6过程总)
I have this example of code, but I don't understand why this code creates 5 processes plus the original. (6 process total)
#include <unistd.h>
int main(void) {
int i;
for (i = 0; i < 3; i++) {
if (fork() && (i == 1)) {
break;
}
}
}
推荐答案
叉()
分为二的处理,并返回为0(如果这个过程是儿童),或儿童的PID(如果该过程是父)。所以,这一行:
fork()
splits a process in two, and returns either 0 (if this process is the child), or the PID of the child (if this process is the parent). So, this line:
if (fork() && (i == 1)) break;
说如果这是父进程,这是第二次通过循环,跳出循环。这意味着循环运行是这样的:
Says "if this is the parent process, and this is the second time through the loop, break out of the loop". This means the loop runs like this:
-
我== 0
:第一次循环,I
0,我们创造两个过程,无论是在进入循环我== 1
。 总现在两个进程
i == 0
: The first time through the loop,i
is 0, we create two processes, both entering the loop ati == 1
. Total now two processes
我== 1
:这两项进程叉,但他们两个不继续,因为如果迭代(叉()及及(我== 1))断裂;
线(两个不继续父母双方都在叉呼叫)。 总现在四个过程,但只有两个那些还在不断地循环。
i == 1
: Both of those processes fork, but two of them do not continue to iterate because of the if (fork() && (i == 1)) break;
line (the two that don't continue are both of the parents in the fork calls). Total now four processes, but only two of those are continuing to loop.
我== 2
:现在,这两个是继续循环两个叉,造成6过程
i == 2
: Now, the two that continue the loop both fork, resulting in 6 processes.
我== 3
:所有6过程退出循环(因为我3;假==
,没有更多的循环)
i == 3
: All 6 processes exit the loop (since i < 3 == false
, there is no more looping)
这篇关于我不明白叉的这个例子中()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!