当孩子们叉子时fork()如何工作?

Bab*_*ani 3 c unix fork wait

我已经执行了一段代码.它如下所示:

#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)


Fre*_*Foo 6

该程序生成一个进程树.每一fork棵树都分成两半.如果你拿一张纸,画这棵树并不是很难; 唯一困难的是i由于你使用前缀而使值正确++.如果您sleep在结束时让每个过程持续几秒钟,您还可以使用该pstree程序观察树.

然后,每个进程都运行wait系统调用,该系统调用等待其子进程中的任何一个(进程树中的子节点)完成.

  • 不是第一个,如果我们想要迂腐,但*任何*孩子,对吧? (3认同)