当前位置: 首页 > news >正文

Linux系统编程——进程中vfork函数

函数原型

pid_t vfork(void);//pid_t是无符号整型

所需头文件

#include <sys/types.h>
#include <unistd.h>

功能

vfork() 函数和 fork() 函数一样都是在已有的进程中创建一个新的进程,但它们创建的子进程是有区别的。

返回值

成功子进程中返回 0,父进程中返回子进程 ID
失败返回 -1

vfork与fork的区别

关键区别一:

fork执行时无先后顺序,父进程与子进程会争夺执行 

vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行

代码验证

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
	int fork_t = 0;

	fork_t = fork();

	if(fork_t > 0)
	{
		while(1)		
		{
			printf("This is father\n");
			sleep(1);
		}
	}
	else if(fork_t == 0)
	{
		while(1)
		{
			printf("This is child\n");
			sleep(1);
		}
				
	}
	return 0;
}

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
	int vfork_t = 0;
	int count = 0;

	vfork_t = vfork();

	if(vfork_t > 0)
	{
		while(1)		
		{
			printf("This is father\n");
			sleep(1);
		}
	}
	else if(vfork_t == 0)
	{
		while(1)
		{
			printf("This is child\n");
			sleep(1);
			count++;
			if(count >= 3)
			{
				exit(-1);//输出三次子进程,之后退出
			}
		}
				
	}
	return 0;
}

第一部分代码可见fork函数中的父进程和子进程会争夺输出,而第二部分的vfork函数会在子进程输出3次退出之后再执行父进程。


关键区别二:

fork中子进程会拷贝父进程的所有数据,子进程是父进程的地址空间

vfork中子进程共享父进程的地址空间

代码验证

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
	int fork_t = 0;
	int a = 10;

	fork_t = fork();
	
	if(fork_t != 0)
	{
		printf("This is father,a = %d\n",a);
	}
	else
	{
		printf("This is child,a = %d\n",a);
	}
	return 0;
}

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
	int vfork_t = 0;
	int count = 0;

	vfork_t = vfork();

	if(vfork_t > 0)
	{
		while(1)		
		{	
			printf("count = %d\n",count);
			printf("This is father\n");
			sleep(1);
		}
	}
	else if(vfork_t == 0)
	{
		while(1)
		{
			printf("This is child\n");
			sleep(1);
			count++;
			if(count >= 3)
			{
				exit(0);
			}
		}
				
	}
	return 0;
}

第一部分代码可知,在父进程中定义a,调用fork函数时,父进程与子进程打印a的值一样,说明子进程会拷贝父进程的所有数据(父进程的只打印自己的值,不会收子进程影响);第二部分代码可知,在子进程结束之后,才会执行父进程,且子进程中数值发生改变,在父进程调用时会发生改变(一开始父进程a=0,调用后a=3),会受到子进程影响

http://www.dtcms.com/a/4112.html

相关文章:

  • vue3使用element-plus
  • Python---数据序列中的公共方法
  • 性能测试 —— Jmeter接口处理不低于200次/秒-场景
  • table表格的某一行数据如何回填
  • spark调优案例分享
  • ADFS 高可用配置 + NLB配置(Windows网络负载均衡)
  • 减轻关键基础设施网络安全风险的 3 种方法
  • jupyter lab配置列表清单
  • Python基础入门----如何使用 Pipenv 在项目目录中创建虚拟环境
  • 前端---认识JS
  • 大环境之下软件测试行业趋势能否上升?
  • Oracle(17)Managing Roles
  • 低代码编辑平台后台实现
  • 十个使用Spring Cloud和Java创建微服务的实践案例
  • 应届裁员,天胡开局——谈谈我的前端一年经历
  • keepalived+haproxy配置集群和负载均衡
  • JavaScript + setInterval实现简易数据轮播效果
  • 相机内外参实践之点云投影矢量图
  • 基于鸽群算法优化概率神经网络PNN的分类预测 - 附代码
  • DEC 深度编码聚类函数
  • Java可以传入任意类的公共类写法
  • 【Liunx】部署MariaDB
  • 儿童水杯上架亚马逊美国站CPC认证办理 ,常见儿童产品CPC认证测试要求
  • js控制手机蓝牙
  • pytorch框架学习(tensorboard的使用)
  • IP-guard flexpaper远程命令执行漏洞复现 [附POC]
  • 搜索引擎项目
  • 信道复用技术
  • ssm823基于ssm的心理预约咨询管理系统的设计与实现+vue
  • 如何实现MQTT协议数据传输?