叉混淆() [英] Confused with fork()
问题描述
我有困难的时候理解不同情景下fork()的命令做了什么。下面是我的一些书样本code:
INT的main(){
int类型的= 12;
INT B = 9;
INT FID = fork()的; 如果(FID == 0){
一个++;
}
其他{
等待(NULL);
B = - 5;
} 的printf(程序退出时=%D,B =%d个\\ n,A,B);
返回0;
}
有人能走我通过什么叉()命令在这种情况下,这样做或许能给一些例子,以澄清?
[主]
一个= 12
B = 9 叉子()
|
|
+ -------------- -------------- + +
| |
| |
[家长] [儿童]FID = 1234 FID = 0
等待(NULL)一++
...的printf(A = 13,B = 9);
...返回0
...<退出>
B = - 5
输出(α= 12时,b = 4);
返回0
<退出>
在叉()
执行有计划的两个副本。每个进程都有自己的变量副本,所以现在有两个 A
的两个 B
的,等两个方案之间的唯一区别是叉从返回的值()
:在子进程叉()
返回0;在父进程返回子的PID。
子进程增量 A
,打印 A
和 B 值code>,并退出
父进程首先等待子进程终止。孩子已经完成了它继续,从减去5 B
,打印出只有在 A
和 b
,然后退出。
的等待(NULL)
确保子进程的打印始终到来之前父母的,所以你总是会得到一个可靠的订单相同的输出。没有它,你就无法依靠两个打印输出的数量级上。他们将是相同的消息,只是在未predictable秩序。
I am having a difficult time understanding what the fork() command does under different scenarios. Here is some sample code from my book:
int main() {
int a = 12;
int b = 9;
int fid = fork();
if (fid == 0) {
a++;
}
else {
wait(NULL);
b = b - 5;
}
printf("program exit. a = %d, b = %d\n", a, b);
return 0;
}
Can someone walk me through what the fork() command is doing in this case and perhaps give some more examples to clarify?
[main]
a = 12
b = 9
fork()
|
|
+--------------+--------------+
| |
| |
[parent] [child]
fid = 1234 fid = 0
wait(NULL) a++
... printf("a = 13, b = 9");
... return 0
... <exit>
b = b - 5
printf("a = 12, b = 4");
return 0
<exit>
After fork()
executes there are two copies of the program. Each process gets its own copies of the variables, so there are now two a
's, two b
's, etc. The only difference between the two programs is the value returned from fork()
: in the child process fork()
returns 0; in the parent process it returns the PID of the child.
The child process increments a
, prints the values of a
and b
, and exits.
The parent process first waits for the child process to terminate. Only after the child has finished does it continue on, subtracting 5 from b
, printing out a
and b
, and then exiting.
The wait(NULL)
ensures that the child process's printout always comes before the parent's, so you will always get the same output in a reliable order. Without it you wouldn't be able to depend on the order of the two printouts. They would be the same messages, just in an unpredictable order.
这篇关于叉混淆()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!