fork与vfork的区别:
验证vfork保证子进程先运行,当子进程调用exit退出后,父进程才能进行
代码:
运行结果:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int cnt;
pid=vfork();
if(pid>0){
while(1){
printf("this is father print,pid=%d\n",getpid());
sleep(2);
printf("cnt:%d\n",cnt);
}
}else if(pid==0){
while(1){
printf("this is child print,pid=%d\n",getpid());
sleep(2);
cnt++;
if(cnt==3){
exit(-1);
}
}
}
return 0;
}
CLC@Embed_Learn:~/lianxi4$ gcc demo1.c
CLC@Embed_Learn:~/lianxi4$ ./a.out
this is child print,pid=25895
this is child print,pid=25895
this is child print,pid=25895
this is father print,pid=25894
cnt:3
this is father print,pid=25894
cnt:3
this is father print,pid=25894
cnt:3
备注:因为vfork直接使用父进程的储存空间,而不进行拷贝,所以子进程中改变的cnt的值,在父进程中也变成3