博客
关于我
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/

你可能感兴趣的文章
Oracle dbms_job.submit参数错误导致问题(ora-12011 无法执行1作业)
查看>>
oracle dg switchover,DG Switchover fails
查看>>
Oracle E-Business Suite软件 任意文件上传漏洞(CVE-2022-21587)
查看>>
Oracle EBS OPM 发放生产批
查看>>
Oracle EBS-SQL (BOM-15):检查多层BOM(含common BOM).sql
查看>>
Oracle EBS环境下查找数据源(OAF篇)
查看>>
oracle Extract 函数
查看>>
uni-app开发环境自动部署的一个误区(App running at...)
查看>>
Oracle GoldenGate Director安装和配置(无图)
查看>>
oracle instr函数详解
查看>>
Oracle Java所有版本的下载链接
查看>>
oracle ogg 单实例双向复制搭建(oracle-oracle)--Oracle GoldenGate
查看>>
oracle ORA-14402 OGG-01296
查看>>
oracle partition by list,深入解析partition-list 分区
查看>>
Oracle PL/SQL Dev工具(破解版)被植入勒索病毒的安全预警及自查通告
查看>>
oracle rac集群的东西之QQ聊天
查看>>
Oracle Schema Objects——Tables——Table Compression
查看>>
oracle scott趣事
查看>>
oracle script
查看>>
Oracle select表要带双引号的原因
查看>>