vfork()直接使用父进程存储空间,不拷贝
fork()函数
1 #include<stdio.h>
2 #include <unistd.h>
3
4 int main()
5 {
6 int data=10;
7 // pid_t getpid(void);
8 printf("before fork pid is %d\n",getpid());
9 // pid_t fork(void);
10 pid_t pid;
11 pid = fork();
12 printf("after fork pid is %d\n",getpid());
13
14 if(pid == 0 ){
15 printf("This is child process and pid is %d\n",getpid());
16 data+=20;
17 }else if(pid > 0){
18 printf("This is father process and pid is %d\n",getpid());
19 }
20
21 printf("data = %d\n",data);
22 return 0;
23 }
vfork()函数
1 #include<stdio.h>
2 #include<unistd.h>
3 #include<stdlib.h>
4
5 int main()
6 {
7 int data=10;
8 int cnt=0;
9 // pid_t getpid(void);
10 printf("before fork pid is %d\n",getpid());
11 // pid_t fork(void);
12 pid_t pid;
13 pid = vfork();
14 printf("after fork pid is %d\n",getpid());
15
16 if(pid == 0){
17 while(1){
18 printf("This is child process and pid is %d\n",getpid());
19 data+=20;
20 sleep(1);
21 cnt++;
22 if(cnt==5){
23 exit(0);
24 }
25 }
26 }else if(pid > 0){
27 printf("This is father process and pid is %d\n",getpid());
28 printf("PID=%d\n",pid);
29 }
30
31 printf("data = %d\n",data);
32 return 0;
33 }