vfork与fork都可以创建进程,但有两个区别
关键区别一:
vfork直接使用父进程存储空间,不拷贝。
关键区别二:
vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行。
使用fork()创建进程
int main()
{
int fork_r=0;
fork_r=fork();//新建进程
if(fork_r!=0){
//父进程
while(1){
printf("this is the father process!\n");
sleep(2);
}
}else{
//子进程
while(1){
printf("this is the child process!\n");
sleep(2);
}
}
}
使用vfork()创建进程
int main()
{
int cnt =0;
int fork_r=0;
fork_r=vfork();
if(fork_r!=0){
//父进程
while(1){
printf("this is the father process!\n");
sleep(2);
printf("cnt =%d\n",cnt);
}
}else{
//子进程
while(1){
printf("this is the child process!\n");
sleep(2);
if(cnt == 3){
exit(0);
}
cnt++;
}
}
}