博客
关于我
15LinuxC进程间通信之mmap无血缘进程间通信
阅读量:238 次
发布时间:2019-03-01

本文共 1727 字,大约阅读时间需要 5 分钟。

mmap无血缘进程间通信

1. 写文件

#include 
#include
#include
#include
#include
#include
#include
#include
typedef struct Student { int id; char name[64]; int age;} student;void sys_err(const char *str) { perror(str); exit(1);}int main(void) { struct student stu = {1, "xiaoming", 18}; struct student *p = NULL; int fd; fd = open("test_map", O_RDWR | O_CREAT | O_TRUNC, 0664); if (fd == -1) { sys_err("open failed."); } 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++; } munmap(p, sizeof(stu)); return 0;}

2. 读文件

#include 
#include
#include
#include
#include
#include
#include
#include
typedef struct Student { int id; char name[64]; int age;} student;void sys_err(const char *str) { perror(str); exit(1);}int main(void) { struct student stu; struct student *p = NULL; int fd; fd = open("test_map", O_RDONLY, 0664); if (fd == -1) { sys_err("open failed."); } 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) { printf("id=%d, name=%s, age=%d\n", p->id, p->name, p->age); } munmap(p, sizeof(stu)); return 0;}

由于我们开辟的映射区刚好是一个stu的大小,可能会因为读取速度较慢而导致前面的一些student类型数据被覆盖。


2. 多个进程读写mmap

将写程序的open命令去掉O_TRUNC标志,确保多个进程在写入时文件可以追加。

1)多个进程写入单个读者可以看到,mmap允许重复读取,因为文件内容不会改变。而使用管道(pipe)和首次入先出(fifo)则不同,管道中的数据一读就丢失。


3. 总结

  • mmap允许数据重复读取,而pipefifo只能读取一次。
  • mmap无血缘进程间通信的根本原因是共享相同的映射区,而pipefifo则依赖于共享的管道。从这个角度来看,fifo也可以看作是无血缘通信的一种实现方式。

转载地址:http://osfv.baihongyu.com/

你可能感兴趣的文章
ObsoleteAttribute 可适用于除程序集、模块、参数或返回值以外的所有程序元素。 将元素标记为过时可以通知用户:该元素在产品的未来版本中将被移除。...
查看>>
OC Xcode快捷键
查看>>
oc 中的.m和.mm文件区别
查看>>
OC 内存管理黄金法则
查看>>
oc57--Category 分类
查看>>
occi库在oracle官网的下载针对vs2008
查看>>
OceanBase 安装使用详细说明
查看>>
OceanBase详解及如何通过MySQL的lib库进行连接
查看>>
OCP题库升级,新版的052考试题及答案整理-18
查看>>
OCR使用总结
查看>>
OfficeWeb365 SaveDraw 文件上传漏洞复现
查看>>
office中的所有content type
查看>>
office之Excel 你会用 Ctrl + E 吗?
查看>>
Office办公软件里的“开发工具”选项卡-ChatGPT4o作答
查看>>
Offline Installation the .NET Framework 3.5 on Windows 8
查看>>
OGG初始化之使用数据库实用程序加载数据
查看>>
ogg参数解析
查看>>
ognl详解
查看>>
Ogre 插件系统
查看>>
Oil Deposits
查看>>