转自:https://blog.csdn.net/jianchi88/article/details/6985326
1.vfork()创建子进程,在调用exec()之前或exit()之前,子进程与父进程共享数据段(与fork()不同,fork要拷贝父进程的数据段,堆栈段)
2.调用vfork()后,子进程先执行,父进程被挂起,直到子进程调用了exec或exit之后,父进程才执行。
例子1:
fork()
#include <unistd.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
int cnt = 1;
pid_t pid = fork();
if(pid<0){
printf("process error!!\n");
return 1;
}
else if(pid==0){
printf("this is a child process, id = %d, count =%d \n",getpid(),cnt++);
}
else
printf("this is the parent process, id = %d, count =%d \n",getpid(),cnt++);
return 0;
}
子进程拷贝父进程的数据段,堆栈段。处于不同的内存位置,所以cnt都是1
输出:
this is the parent process, id = 2661, count =1
this is a child process, id = 2664, count =1
例子2:
使用vfork(),但子进程不调用exit()或exec(),父进程一直挂起
导致死锁!
#include <unistd.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
int cnt = 1;
pid_t pid = vfork();
if(pid<0){
printf("process error!!\n");
return 1;
}
else if(pid==0){
printf("this is a child process, id = %d, count =%d \n",getpid(),cnt++);
}
else
printf("this is the parent process, id = %d, count =%d \n",getpid(),cnt++);
return 0;
}
输出:
this is a child process, id = 3248, count =1
this is the parent process, id = 3247, count =4195584
vfork: cxa_atexit.c:100: __new_exitfn: Assertion `l != NULL' failed.
已放弃 (核心已转储)
例子3:
使用vfork(),并且子进程调用exit()或exec()
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int cnt = 1;
pid_t pid = vfork();
if(pid<0){
printf("process error!!\n");
return 1;
}
else if(pid==0){
printf("this is a child process, id = %d, count =%d \n",getpid(),cnt++);
exit(1);
}
else
printf("this is the parent process, id = %d, count =%d \n",getpid(),cnt++);
return 0;
}
子进程执行exit(1)退出后,父进程开始执行,由于共享数据段,所以cnt在子进程加1的基础上再加1 =2
this is a child process, id = 3497, count =1
this is the parent process, id = 3496, count =2