我已经执行了一段代码.它如下所示:
#include<stdio.h>
main() {
int i=0;
fork();
printf("The value of i is:%d\n",++i);
fork();
printf("The value of j is:%d\n",++i);
fork();
wait();
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
The value of i is:1
The value of j is:2
The value of i is:1
The value of j is:2
The value of j is:2
pckoders@ubuntu:~$ The value of j is:2
Run Code Online (Sandbox Code Playgroud)
任何人都可以向我解释fork()和wait()函数在这里扮演什么角色?
Gre*_*ape 11
fork()
电话是一个字面上的分叉.完成后,您将拥有2个具有精确堆栈的精确进程,并且所有描述符都指向相同的对象.您可以通过返回值区分它们.对于子进程fork()
返回0,表示父 - 子进程ID.
所以
main() {
int i=0;
fork();
// at this point you are having 2 processes. stdout and stdin are basically just dupplicates.
// (P)
// / \
// (P) (C)
// prints1 prints 1
printf("The value of i is:%d\n",++i); // so 2 processes with print 1
fork();
// now you are having 4 processes( both parent and children forked)
// (P)
// / \
// / \
// (P) (C)
// / \ / \
// (PP) (PC) (CP) (CC)
// prints 2 prints 2 prints 2 prints 2
printf("The value of j is:%d\n",++i);
fork();
// now 4 processes are forking. now you have 8 processes
// (P)
// / \
// / \
// / \
// (P) (C)
// / \ / \
// / \ / \
// (PP) (PC) (CP) (CC)
// / \ / \ / \ / \
// (PPP) (PPC) (PCP) (PCC) (CPP) (CPC) (CCP) (CCC)
wait();
}
Run Code Online (Sandbox Code Playgroud)
该程序生成一个进程树.每一fork
棵树都分成两半.如果你拿一张纸,画这棵树并不是很难; 唯一困难的是i
由于你使用前缀而使值正确++
.如果您sleep
在结束时让每个过程持续几秒钟,您还可以使用该pstree
程序观察树.
然后,每个进程都运行wait
系统调用,该系统调用等待其子进程中的任何一个(进程树中的子节点)完成.