IPC研究(5) -- 共享内存(shared memory)
发布日期:2021-08-31 01:31:49 浏览次数:3 分类:技术文章

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

hot3.png

==================================================

IPC
SystemV IPC shared memory
==================================================
Related System Calls
#include <sys/shm.h>
void *shmat(int shm_id, const void *shm_addr, int shmflg);//attach the shm to the address space of a process to make it accessible
int shmctl(int shm_id, int cmd, struct shmid_ds *buf); //control function for shm
int shmdt(const void *shm_addr); //detach the shm
int shmget(key_t key, size_t size, int shmflg);//create or open a shm

===================================================

Basic
When you first create a shared memory segment, it’s not accessible by any process. To enable access to the
shared memory, you must attach it to the address space of a process.

The second parameter, shm_addr, is the address at which the shared memory is to be attached to the

current process. This should almost always be a null pointer, which allows the system to choose the
address at which the memory appears.

Permissions on shared memory are similar to the permissions on files. (comment: this is good!)

 

===================================================

Analysis
shmget这个函数和semget这个函数的用法非常类似,都是用key来得到(或者创建)一个进程间的共有资源。
IPC_PRIVATE = 0
通常不要使用IPC_PRIVATE做为key。

Shared Memory的通信方式很直观,就是几个进程都能看见某块physical segment,然后大家都在读写这块physical segment.

由以上的通信方式,我们容易想到以下几个问题。
1. 因为shared memory明显和进程的私有地址不一样,所以必须要做特殊声明(或者说创建)。shmget提供这个功能。
2. 某个进程必须将这块physical segment映射到其logical address才可以进行访问;另外,当它不像再访问这块内存时,应该要解除这种映射。shmat和shmdt提供了这两个功能。
3. 进程必须要能控制这块memory,包括能知道它的状态,修改状态,删除它等。由shmctl来提供这些控制功能。
4. shared memory它就是块内存,几个进程同时对它访问,毫无疑问会出竞争状态。所以,通常需要在进程间做同步。于是,进程间的约定就要包括共同的key值的约定和同步的约定。如果仅

适用shared memory中某一块的值来进行同步,会出现两个问题:真正的并发问题(因为通常对某个值得读写并不是原子操作)和busy waiting带来的CPU资源消耗。所以,我们同步必须要用

到其他的IPC机制,比如semaphore。

5. 同一个资源访问时的权限问题。(这个目前没什么研究,后续补充)

 

转载于:https://my.oschina.net/u/158589/blog/56638

转载地址:https://blog.csdn.net/weixin_34056162/article/details/91981692 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:how to build redmine for project management
下一篇:JS动态可控制左右滚动的图片代码

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月17日 00时13分43秒