Linux vfork()

转自: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 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值