IPC研究(5) -- 共享内存(shared memory)

==================================================
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. app

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!)this

 

===================================================
Analysis
shmget这个函数和semget这个函数的用法很是相似,都是用key来获得(或者建立)一个进程间的共有资源。
IPC_PRIVATE = 0
一般不要使用IPC_PRIVATE作为key。spa

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. 同一个资源访问时的权限问题。(这个目前没什么研究,后续补充)资源

相关文章
相关标签/搜索