利用共享記憶體實現多程序互動
阿新 • • 發佈:2019-02-09
一、什麼是共享記憶體?
共享記憶體(shared memory)是Unix下的多程序之間的通訊方法,這種方法通常用於一個程式的多程序間通訊,實際上多個程式間也可以通過共享記憶體來傳遞資訊。共享記憶體指在多處理器的計算機系統中,可以被不同中央處理器(CPU)訪問的大容量記憶體。由於多個CPU需要快速訪問儲存器,這樣就要對儲存器進行快取(Cache)。共享記憶體是存在於核心級別的一種資源,在shell中可以使用ipcs命令來檢視當前系統IPC中的狀態,在檔案系統/proc目錄下有對其描述的相應檔案。共享記憶體相比其他幾種方式有著更方便的資料控制能力,資料在讀寫過程中會更透明。二、共享記憶體的介面API
Linux提供了一組函式介面用於使用共享記憶體,它們宣告在標頭檔案 sys/shm.h中。1、shmget函式該函式用來建立共享記憶體,它的原型為:- int shmget(key_t key, size_t size, int shmflg);
第一個引數,程式需要提供一個引數key(非0整數),它有效地為共享記憶體段命名,shmget函式成功時返回一個與key相關的共享記憶體識別符號(非負整數),用於後續的共享記憶體函式。呼叫失敗返回-1.shmget() returns the identifier of the System V shared memory segment associated with the value of the argument key. A new shared memory segment, with size equal to the value of size rounded up to a multiple of PAGE_SIZE, is created if key has the value IPC_PRIVATE or key isn't IPC_PRIVATE, no shared memory segment corresponding to key exists, and IPC_CREAT is specified in shmflg.
- void *shmat(int shm_id, constvoid *shm_addr, int shmflg);
- int shmdt(constvoid *shmaddr);
引數shmaddr是shmat函式返回的地址指標,呼叫成功時返回0,失敗時返回-1.
4、shmctl函式
與訊號量的semctl函式一樣,用來控制共享記憶體,它的原型如下:- int shmctl(int shm_id, int command, struct shmid_ds *buf);
IPC_RMID:刪除共享記憶體段
第三個引數,buf是一個結構指標,它指向共享記憶體模式和訪問許可權的結構。shmid_ds結構至少包括以下成員:
- struct shmid_ds
- {
- uid_t shm_perm.uid;
- uid_t shm_perm.gid;
- mode_t shm_perm.mode;
- };
三、多程序互動得小專案實戰框架,原始碼在這個連結之中,需要請自行下載。
http://download.csdn.net/download/sinat_34866256/10261546