当前位置: 技术问答>linux和unix
请教对fork()的理解
来源: 互联网 发布时间:2016-01-06
本文导语: # include "unistd.h" # include "stdio.h" # include "sys/types.h" # include "sys/wait.h" main() {int i=0; if(!fork()) {printf("into 1n"); } if(!fork()) {printf("into 2n"); } printf("i=%dn",i++); } 运行后输出结果为: into 1 into 2 i=0 i=0 into 2 i=0 i=0 请问...
# include "unistd.h"
# include "stdio.h"
# include "sys/types.h"
# include "sys/wait.h"
main()
{int i=0;
if(!fork())
{printf("into 1n");
}
if(!fork())
{printf("into 2n");
}
printf("i=%dn",i++);
}
运行后输出结果为:
into 1
into 2
i=0
i=0
into 2
i=0
i=0
请问是如何得出结果的?
# include "stdio.h"
# include "sys/types.h"
# include "sys/wait.h"
main()
{int i=0;
if(!fork())
{printf("into 1n");
}
if(!fork())
{printf("into 2n");
}
printf("i=%dn",i++);
}
运行后输出结果为:
into 1
into 2
i=0
i=0
into 2
i=0
i=0
请问是如何得出结果的?
|
a->fork ->into 1
______b ->fork ->into 2
____________c -> i=0 end
________________________b -> i=0 end
__________________a ->fork ->into 2
________________________d -> -> i=0 end
____________________________________a -> i=0 end
fork: a b c d
______b ->fork ->into 2
____________c -> i=0 end
________________________b -> i=0 end
__________________a ->fork ->into 2
________________________d -> -> i=0 end
____________________________________a -> i=0 end
fork: a b c d
|
子进程和父进程共享代码段,fork()后,父子进程分别从fork()后的语句开始执行
上面的语句就是从对fork()返回值的判断语句开始,父子进程分别进入不同的分支执行
上面的语句就是从对fork()返回值的判断语句开始,父子进程分别进入不同的分支执行