进程篇—你所不知道的fork
标签:fork
一、fork用法
作用是创建进程,
函数原型:
include
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 int main()
5 {
6 pid_t pid=fork();
7 if(pid < 0)
8 {
9 printf("error\n");
10 }
11 else if(pid==0)
12 {
13 printf("I am children,process is %d\n",getpid());
14 }
15 else
16 {
17 printf("I am father,process is %d\n\n",getppid());
18 }
19 return 0;
20 }
结果:
I am father,process is 2749
I am children,process is 3516
子进程是父进程的副本,它将获得父进程数据空间、堆、栈等资源的副本。注意,子进程持有的是上述存储空间的“副本”,这意味着父子进程间不共享这些存储空间,他们共享代码段。
UNIX将复制父进程的地址空间内容给子进程,因此,子进程有了独立的地址空间。在不同的UNIX(Like)系统下,我们无法确定fork之后是子进程先运行还是父进程先运行,这依赖于系统的实现。
代码可以很好的表现出来:
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 int a=5;
5 int main()
6 {
7 pid_t pid=fork();
8 if(pid < 0)
9 {
10 printf("error\n");
11 }
12 else if(pid==0)
13 {
14 a++;
15 printf("I am children,process is %d,a=%d\n",getpid(),a);
16 }
17 else
18 {
19 printf("I am father,process is %d,a=%d\n",getppid(),a);
20 }
21 return 0;
22 }
结果:
I am father,process is 2749,a=5`
I am children,process is 4565,a=6
由上面代码可以看出,子进程虽然复制了父进程的堆栈等,但是他们之间是不共享的。