[英]How does fork work on this program?
I've got this program 我有这个程序
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x =1;
int* y = malloc(sizeof(int));
*y = 2;
if (fork()==0)
x++;
if (fork()==0)
(*y)++;
printf("%d", (x+*y));
}
Here's the output 3445. This is what I know so far, fork() creates a new child process. 这是输出3445。到目前为止,这是我所知道的,fork()创建了一个新的子进程。 0 is returned by fork() if it's the child process and PID if it's the parent process. 如果是子进程,则fork()返回0;如果是父进程,则返回PID。 So once you call fork(), it becomes the parent and fork()==0 is true only on the child process and not the parent. 因此,一旦调用fork(),它将成为父级,而fork()== 0则仅在子进程而非父进程上为true。 Can anyone give me more insight to what's actually happening so that I get that output? 谁能让我对实际发生的事情有更多的了解,以便获得输出结果?
Draw a graph show child-parent relationship and stats of them are vary helpful, here is one possible form (C for child, P for parent): 画一个图来显示孩子与父母之间的关系,它们的统计数据对您有所帮助,这是一种可能的形式(C代表孩子,P代表父母):
fork()
C (x == 2, *y == 2)
fork()
C (x == 2, *y == 3) ==> print 5
P (x == 2, *y == 2) ==> print 4
P (x == 1, *y == 2)
fork()
C (x == 1, *y == 3) ==> print 4
P (x == 1, *y == 2) ==> print 3
So something combination of 5, 3, 4, 4 will be printed, the exact combination depends on the order of these printf()
be called, could be different from run to run . 因此,将打印5、3、4、4的某种组合,确切的组合取决于这些printf()
调用的顺序, 一次运行可能会有所不同 。
fork() returns -1 on error, so you have to check it too. fork()会在错误时返回-1,因此您也必须进行检查。 So it is better to do something like: 因此,最好执行以下操作:
int pid;
pid = fork();
if (pid == 0)
{
//child process code goes here
}
if (pid > 0)
{
//parent process code goes here
}
Note that both processes you have after the first fork() then execute fork() one more time, so you end up with 4 processes. 请注意,您在第一个fork()之后拥有两个进程,然后又执行一次fork(),因此最终得到4个进程。
And, of course, the order of their execution is undefined, so you will get 3, 5 and couple of 4 in different combinations every time you run this. 而且,当然,它们的执行顺序是不确定的,因此每次运行此命令时,您将分别获得3、5和4的不同组合。
Also, beware that some printf(...) and fork() combinations can lead to weird output if you don't call flush(...) before fork(). 另外,请注意,如果不在fork()之前调用flush(...),则某些printf(...)和fork()组合可能导致奇怪的输出。
And finally, you've forget to free(y) at the end, so you leak 4*sizeof(int) bytes every time you run this program. 最后,您忘了最后释放(y),因此每次运行此程序时,您泄漏4 * sizeof(int)个字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.