关键区别1:
vfork直接使用父进程存储空间,不进行拷贝;
关键区别2:
vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行。而fork函数创建完子进程之后不知道先运行父进程还是子进程,需要调度。
int main()
{
pid_t pid;
pid = vfork();
printf("im on\r\n");
if(pid > 0)
{
while(1)
{
printf("this is father thread,id = %d\r\n",getpid());
sleep(2);
}
}else if(pid == 0)
{
while(1)
{
printf("this is child thread,id = %d\r\n",getpid());
sleep(2);
}
}
return 0;
}
代码执行结果:
可以看到,只有子进程一直在运行,父进程没运行,如果是fork函数,那么父进程和子进程会一起运行。
另外关于vfork共享父进程存储空间:
int main()
{
pid_t pid;
int data = 0;
pid = vfork();
printf("im on\r\n");
if(pid > 0)
{
while(1)
{
printf("this is father thread,id = %d\r\n",getpid());
sleep(2);
printf("data = %d\r\n",data); //在父进程打印出data数值
}
}else if(pid == 0)
{
while(1)
{
printf("this is child thread,id = %d\r\n",getpid());
sleep(2);
printf("this is child thread,id = %d\r\n",getpid());
sleep(2);
printf("this is child thread,id = %d\r\n",getpid());
sleep(2);
data +=20; //在子进程中改变data数值,
exit(0);
}
}
return 0;
}
执行结果:
可以看到,data的值被改变了,也就是说,vfork情况下,父子进程使用同一个内存空间。