linux下的vfork()与fork()两个函数的区别,使用方法

本文对比了fork和vfork函数在创建子进程后的运行特性。fork函数创建的父子进程独立运行,顺序不定;而vfork确保子进程先于父进程运行完毕。通过代码示例详细解析了两种函数的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

fork函数创建子进程后,父子进程是独立、同时运行得,而且没有先后顺序
vfork()产生的父子进程,一定是子进程先运行完,再运行父进程

直接上代码

fork()
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>

int main(void)
{
	pid_t child;

	/* 创建子进程 */
	if((child=fork())==-1)
	{
		printf("Fork Error : %s\n", strerror(errno));
		exit(1);
	}
	else 
		if(child==0) // 子进程
		{
			printf("I am the child_pid: %d\n", getpid());
			exit(0);
		}
		else        //父进程
		{
			printf("I am the father_pid:%d\n",getpid());
			return 0;
		}
}	

打印结果:在这里插入图片描述
父子进程无顺序运行

vfork()
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>

int main(void)
{
	pid_t child;

	/* 创建子进程 */
	if((child=vfork())==-1)
	{
		printf("Fork Error : %s\n", strerror(errno));
		exit(1);
	}
	else 
		if(child==0) // 子进程
		{
			sleep(2); //子进程睡眠2秒
			printf("I am the child: %d\n", getpid());
			exit(0);
		}
		else        //父进程
		{
			printf("I am the father:%d\n",getpid());
			exit(0);
		}
}	

结果:
在这里插入图片描述
图中 运行结果 8256的进程是2秒后出现,随后出现8255。

总结 调用fork函数产生的父子进程运行顺序不定,而调用vfork函数,是先子后父。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sf9090

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值