标签:
vfork()学习
vfork()与fork()的一个重要区别, 等待子进程退出后, 父进程才会执行.
1 #include <stdio.h> 2 #include <sys/types.h> 3 #include <unistd.h> 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 }
编译/链接/运行结果如下:
父进程会等待子进程执行, 完成退出后, 父进程才会执行.
标签:
原文地址:http://www.cnblogs.com/zhanglong71/p/5074500.html