Shared Memory
Shared Memory is easily to understand, especially after graspingsemaphore.
Normally, if we execute a piece of program twice (make them running at the same time), variables with the same name will occupy different physical memory. That means if in p1(one of the running
process) the system makes x++, in p2(another running process) the same-name variable x will not be affected.
But sometimes we need that the 2 processes could influence each other for communication, then we can use shared memory.
Similar to semaphore, we use get function to obtain an ID.
int shmget(key_t key, size_t size, int shmflg);
shmget() returns an ID pointing to the shared memory associated to the parameter key. The 2nd argument size indicates the memory size that will be allocated, And we usually set shmflg to 0666
| IPC_CREAT.
After we execute the shmget() function, the memory could not be accessed yet. We should use shmat() to attach the shared memory to the calling process, so that the process could perform operations
on the memory.
void *shmat(int shmid, const void *shmaddr, int shmflg);
shmid is the ID returned by shmget(). If we set shmaddr to (void *)0, the system will find a suitable memory to allocate. And usually we set shmflg to 0.
The opposite one to shmat() is shmdt() -- to detach the shared memory from the calling process so that the process could not operate with it any more unless shmat() again.
The prototype of shmdt() is :
int shmdt(const void *shmaddr);
Finally, we use shmctl() to remove the shared memory.
Usually we useshmctl(shmid, IPC_RMID, 0).
以下是一个小实验,我们用shm1.c来对共享内存写消息,然后用shm2.c来读取。
shm1.c:
shm2.c:
对两段代码编譯执行:
需要注意的是对共享内存的读写并不是原子操作,可能出现读到一半的时候另一个进程重写了共享内存,这样难免会出现错误。 关于这一点,则需要编程人员来控制。
Jason Lee
2009-11-15 p.m
分享到:
相关推荐
【咬人草小记,阅读附答案】 咬人草小记阅读答案.docx
流程图与控制流图课堂小记.流程图与控制流图课堂小记.流程图与控制流图课堂小记.流程图与控制流图课堂小记.流程图与控制流图课堂小记.流程图与控制流图课堂小记.流程图与控制流图课堂小记.流程图与控制流图课堂小记....
TCP-IP小记
很全面的,很实用的,看完提高不少,不管新手老手,都绝对有用
随笔小记.doc
python进行爬虫小记,主要用于python快速入门理解。
环境: Linux s12084 2.6.9-67.ELsmp #1 SMP Wed ...小记一下。以备以后参考。 boost 库做得真好。在windows 平台, linux 平台下编译都很顺利。hp aCC 也宣称对 boost 1.35 完全支持 。 全部编译是很痛苦的过程
c语言理论知识小记
GeoStudio学习小记
海居小记
我做java web 多年的小记,希望能打大家有用
asp.net Jmail组件使用小记
redis安全学习小记1
NULL 博文链接:https://zfwdl2005.iteye.com/blog/1308748
本草缘·种植小记
vuex使用方法,小记总结
PHPweb渗透小记.docx
刘重威将军小记.docx
Sqlite数据库sqlite3命令小记
随笔小记的文档,自己记录的一些文档,仅供参考