Linux进程间通信-基于内存(共享内存)
来源:互联网 发布:android系统源码是什么 编辑:程序博客网 时间:2024/05/22 15:15
写在前面:小生纯业余选手,开此博仅仅是为了积累,纯当笔记来用。如有看官光临小生博客,请不要相信我的代码就是正确的。如果您发现了错误也恳请耽误您一点时间,请您在下面指出来,不胜感激!
如果发现一些笔记的说法完全是错误的请建议我删除!
Linux中查看共享内存的指令ipcs,ipcs -m,ipcs -q,ipcs -s,ipcrm -q shmid
使用内存共享机制实现进程间通信的过程:
使用shmget创建共享内存,得到一个ID
使用shmat把ID映射成虚拟地址(attach)
使用虚拟地址访问内核共享内存(与访问普通内存一样)使用 shmdt卸载虚拟地址
使用shctl删除共享内存 ,其中shctl的作用所有修改/获取共享内存的属性的功能
共享内存的属性包括(key,shmid,owner,perms,byte,nattch,dest)
以下代码展现基于共享内存的进程间通信机制
ftok产生一个key标示着一个共享内存,进程可以通过这个key获取这个共享内存。(这里的这种机制与RSA算法的精神有一点类似)
#include<sys/shm.h>#include<sys/ipc.h>#include<stdio.h>#include<stdlib.h>#include<unistd.h>int main(){ key_t key; int shmid; int *p; key = ftok(".",255); if(key == -1) { printf("ftok error:%m\n"); exit(-1); } shmid = shmget(key,4,IPC_CREAT|IPC_EXCL|0666); if(shmid == -1) { printf("get error:%m\n"); exit(-1); } p = static_cast<int*>(shmat(shmid,0,0)); if(p == (int*)-1) { printf("at error%m\n"); exit(-1); } while(1) { *p = 999; sleep(1); } shmdt(p); shmctl(shmid,IPC_RMID,0); return 0;}
#include<stdio.h>#include<string.h>#include<stdlib.h>#include<signal.h>#include<sys/shm.h>#include<sys/ipc.h>#include<unistd.h>int main(){ key_t key; int shmid; int *p; key = ftok(".",255); if(key == -1) { printf("ftok error:%m\n"); exit(-1); } shmid = shmget(key,4,0); if(shmid == -1) { printf("get error:%m\n"); exit(-1); } p = static_cast<int*>(shmat(shmid,0,0)); if( p == reinterpret_cast<int*>(-1) ) { printf("attach error:%m\n"); exit(-1); } while(1) { sleep(1); printf("%d\n",*p); } return 0; }
0 0
- Linux进程间通信-基于内存(共享内存)
- Linux进程间通信-基于内存(共享队列)
- 撸代码--linux进程通信(基于共享内存)
- Linux c 基于内存的进程通信—共享内存、共享队列(消息队列)
- Linux环境进程间通信: 共享内存
- Linux环境进程间通信:共享内存
- linux环境进程间通信:共享内存
- Linux环境进程间通信: 共享内存
- Linux环境进程间通信 共享内存
- linux进程间通信方式 -- 共享内存
- Linux 进程间通信:共享内存
- Linux环境进程间通信: 共享内存
- Linux环境进程间通信: 共享内存
- linux进程间通信之共享内存
- linux进程间通信之共享内存
- linux进程间共享内存通信详解
- Linux进程间通信 共享内存
- Linux 进程间通信:共享内存(上)
- POJ-3398-Perfect Service
- 线段树简单题
- UIButton解析(iOS7)
- 偶的Android 视频学习之路
- sql oracle如何删除某一用户下所有表数据
- Linux进程间通信-基于内存(共享内存)
- Spring源码学习MVC:HandlerMapping的注册与查找
- uva 10006 Carmichael Numbers
- 查询多个表放在一个集合中用union做连接
- Android与服务器端数据交互(基于SOAP协议整合android+webservice)
- ios中摄像头/相册获取图片,压缩图片,上传服务器方法总结
- 机房收费系统5之视图
- WA 了的uva 10806 - Dijkstra, Dijkstra.
- UVA590- Always on the run