vfork()与fork()的一个重要区别, 等待子进程退出后, 父进程才会执行.
1 #include
2 #include
3 #include
4
5 int globVar = 5;
6
7 int main(void)
8 {
9 pid_t pid;
10 int var = 1, i;
11
12 printf("fork is diffirent with vfrok \n");
13
14 pid = vfork();
15
16 switch(pid) {
17 case 0:
18 i = 3;
19 while(i-- > 0)
20 {
21 printf("Child process is running\n");
22
23 globVar++;
24 var++;
25
26 sleep(1);
27 }
28 printf("Child‘s globVar = %d,var = %d, pid = %d\n",globVar,var,getpid());
29 break;
30 case -1:
31 perror("Process creation failed\n");
32 exit(0);
33 default:
34 i = 5;
35 while(i-- > 0)
36 {
37 printf("Parent process is running\n");
38
39 globVar++;
40 var++;
41
42 sleep(1);
43 }
44 printf("Parent‘s globVar = %d ,var = %d, pid = %d\n", globVar ,var,getpid());
45 exit(0);
46 }
47 }
父进程会等待子进程执行, 完成退出后, 父进程才会执行.