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. 同一個資源訪問時的權限問題。(這個目前沒什麼研究,後續補充)資源

相關文章
相關標籤/搜索