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

你可能感兴趣的文章
percona-xtrabackup 备份
查看>>
Perfect,华为爆出 Redis 宝典,原来 Redis 性能可压榨到极致
查看>>
SpringBoot集成OpenOffice实现doc文档转html
查看>>
Perl Socket传输(带注释)
查看>>
ROS中机器人的强化学习路径规划器
查看>>
rocketmq存储结构_rocketmq 消息存储
查看>>
perl---2012学习笔记
查看>>
Perl6 必应抓取(1):测试版代码
查看>>
perl学习之内置变量
查看>>
perl正则表达式中的常用模式
查看>>
Perl的基本語法
查看>>
perl输出中文有乱码
查看>>
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password). 大数据ssh权限问题 hadoop起不来 hadoopssh错
查看>>
PermissionError:Python 中的 [Errno 13]
查看>>
PermissionError:[Errno 13] 权限被拒绝:‘/manage.py‘
查看>>
Permutation
查看>>
perspective意思_2020年12月英语四级词汇讲解丨考点归纳:perspective
查看>>
PE启动盘和U启动盘(第三十六课)
查看>>
PE文件,节头有感IMAGE_SECTION_HEADER
查看>>
PE查找文件偏移地址
查看>>