让我们假设有一个使用PID = 1的进程,它运行以下代码:
int a = fork();
int b = fork();
printf(“a: %d, b: %d\n”, a, b); 让我们进一步假设新的PID将一个接一个地给出,所以第二个给定的PID将是2,然后是3等等。
一项可能的产出是:
a:2, b:3
a:2, b:0
a:0, b:4
a:0, b:0我在试图理解上述代码的输出时遇到了一些困难,尤其是为什么要使用a:0, b:4和a:2, b:3。
发布于 2016-08-02 09:35:50
你知道的
返回值是子进程中的零和父进程中子进程的id号,或者是错误时的-1。
那么,让我们一步一步地看看这里发生了什么。
调用fork()时,它使用id n创建一个新的子级,然后在子0和父n中返回。
因此,让我们假设我们的进程是pid 1,当第一个fork()被调用时,它用pid 2创建一个进程,然后返回到一个值。a将在进程2 (子进程)中具有值2,在进程1中具有值2(父进程)。
然后,每个进程将调用fork(),并将返回值分配给父进程中的b。在子元素中,b将具有值0。
无论如何,我认为这个模式将简化理解:
主要开始:
|
|
int a = fork(); // It creates a new process, and the old one continues going
|
|-------------------------|
a = 2; /* Parent */ a = 0; // Child
| |
| |
int b = fork(); int b = fork(); // Each one create a new process
| |
| |-----------------------------|
| /* Child -> Parent */ // Child -> Child
| a = 0; b = 4; a = 0; b = 0
|
|
|
|
|-----------------------------|
/* Parent -> Parent */ // Parent -> Child
a = 2; b = 3; a = 2, b = 0; 发布于 2016-08-02 09:35:29
第一个叉之前的:
PID 1 (father)
a = (not in scope yet)
b = (not in scope yet)第一个叉子后的:
PID 1 (father)
a = 2
b = (not in scope yet)
PID 2 (child of 1)
a = 0
b = (not in scope yet)第二个叉子后的:
PID 1 (father)
a = 2
b = 3
PID 2 (child of 1)
a = 0
b = 4
PID 3 (child of 1)
a = 2
b = 0
PID 4 (child of 2)
a = 0
b = 0发布于 2016-08-02 09:41:41
我甚至不想回答你的问题。更多的是关于显示通常使用的模式。如果注释中有适当的代码格式,它可能是一个注释。
使用fork()的基本结构是:
if (int PID = fork() == 0 ) {
//it's a child process
} else {
//it's a parent process
}使用简单
int PID1 = fork();
int PID2 = fork();是非常危险的,因为你几乎肯定会收到Race condition。
https://stackoverflow.com/questions/38716624
复制相似问题