llinux之mmap用于非血缘关系进程间通信

这两段代码展示了如何使用mmap函数在多个进程间共享内存。`mmap_w.c`写入一个学生结构体到映射文件,每秒更新ID并同步到文件。`mmap_r.c`读取同一文件,显示学生结构体的ID、姓名和年龄,每秒刷新。通过mmap,实现了进程间的高效数据通信。
摘要由CSDN通过智能技术生成

 代码:mmap_w.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

struct Student{
	int id;
	char name[20];
	int age;
};

void sys_err(char *str)
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	int fd;
	struct Student stu = {1,"xiaoming",18};
	struct Student *p;//用于接收mmap函数返回值
	
	fd = open("testmap",O_RDWR|O_CREAT|O_TRUNC,0664);
	if(fd==-1) sys_err("open");
	
	ftruncate(fd,sizeof(stu));
	
	p = mmap(NULL,sizeof(stu),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
	if(p==MAP_FAILED) sys_err("mmap error");
	close(fd);
	
	while(1){
		memcpy(p,&stu,sizeof(stu));
		stu.id++;
		sleep(1);
	}
	
	munmap(p,sizeof(stu));
	
	return 0;
}

代码:mmap_r.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

struct Student{
	int id;
	char name[20];
	int age;
};

void sys_err(char *str)
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	int fd;
	struct Student stu;
	struct Student *p;//用于接收mmap函数返回值
	
	fd = open("testmap",O_RDONLY);
	if(fd==-1) sys_err("open");
	
	p = mmap(NULL,sizeof(stu),PROT_READ,MAP_SHARED,fd,0);
	if(p==MAP_FAILED) sys_err("mmap error");
	close(fd);
	
	while(1){
		printf("id = %d, name = %s, age = %d\n",p->id,p->name,p->age);
		sleep(1);
	}
	
	munmap(p,sizeof(stu));
	
	return 0;
}

 结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值