关键区别一:
vfork先保证子进程运行,当子进程调用exit退出后,父进程才执行
代码示例
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = vfork();//创建子进程
if(pid > 0)//父进程执行
{
while(1)
{
printf("this is father print = %d\n",getpid());
sleep(1);
}
}
else if(pid == 0)//子进程执行
{
while(1)
{
printf("this is child print,child pid = %d\n",getpid());
sleep(1);
}
}
return 0;
}
编译运行可以看到子进程一直在输出,父进程并没有打印this is father print
修改部分代码 子进程打印三次后退出
else if(pid == 0)
{
while(1)
{
printf("this is child print,child pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 3)
{
exit(0);
}
}
}
编译运行可以看到在子进程退出后父进程开始运行
关键区别二:
vofork直接使用父进程存储空间,不拷贝
修改部分代码,让父进程打印cnt
if(pid > 0)
{
while(1)
{
printf("cnt = %d\n",cnt);
printf("this is father print = %d\n",getpid());
sleep(1);
}
}
通过运行结果可以看到,父子进程中的cnt是同一个地址