fork和vfork的区别
fork和vfork的区别:
- fork: 创建的子进程是拷贝父亲进程的数据段,不共用数据段
vfork:子进程和父进程共用数据段
2. fork: 子进程和父进程的执行次序不确定
vfork:子进程先运行父进程后运行
一下两个例子分别使用fork和vfork创建子进程,验证结果
View Code
1 #include <unistd.h> 2 #include <stdio.h> 3 int main() 4 { 5 int count = 0; 6 pid_t pid; 7 pid = fork(); 8 count++; 9 if(pid < 0) 10 { 11 printf("error in fork\n"); 12 } 13 else if(0 == pid){ 14 printf("This id child process, count = %d\n", count);//count=1 15 } 16 else{ 17 printf("This is parent proccess, count = %d\n", count);//count=1 18 } 19 20 return 0; 21 }
View Code
1 #include <unistd.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 int main() 5 { 6 int count = 0; 7 pid_t pid; 8 pid = vfork(); 9 count++; 10 if(pid < 0) 11 { 12 printf("error in fork\n"); 13 } 14 else if(0 == pid){ 15 printf("This id child process, count = %d\n", count);//count=1 16 exit(0); 17 } 18 else{ 19 printf("This is parent proccess, count = %d\n", count);//count=2 20 } 21 22 return 0; 23 }