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