Linux XSI IPC 之共享記憶體

2021-06-13 21:42:19 字數 1689 閱讀 1177

共享記憶體基礎知識01

共享記憶體基礎知識02

注意:如果在**中沒有手動刪除,共享記憶體並不會隨著程式的終止而自動清理!

其中:第一列就是共享記憶體的key;

第二列是共享記憶體的編號shmid;

第三列就是建立的使用者owner;

第四列就是許可權perms;

第五列為建立的大小bytes;

第六列為連線到共享記憶體的程序數nattach;

第七列是共享記憶體的狀態status。其中顯示「dest」表示共享記憶體段已經被刪除,但是還有使用者在使用它,當該段記憶體的mode欄位設定為shm_dest時就會顯示「dest」。當使用者呼叫shmctl的ipc_rmid時,記憶體先檢視多少個程序與這個記憶體關聯著,如果關聯數為0,就會銷毀這段共享記憶體,否者設定這段記憶體的mod的mode位為shm_dest,如果所有程序都不用則刪除這段共享記憶體。

圖中所有者為root的共享記憶體區是我剛才建立的,我們來檢視一下這段共享記憶體的具體資訊:輸入shell命令:ipcs -m -i 2654237   

如果程式中沒有刪除它,此時,我們可以使用shell命令:ipcrm shmid  來刪除指定共享記憶體區。(示例:ipcrm 2654237)

下面是自己寫的乙個示例。詳細介紹了使用共享記憶體的主要步驟,以及對共享記憶體進行操作之前,使用訊號量機制進行同步保護。當然,大家也可以使用記錄鎖來進行同步。

server.c

#include #include #include #include #include #include #include #include #define ipckey 0x19890319  //為增強可移植性,自定義key_t 

#ifdef _sem_semun_undefined //關於訊號量的知識,可以檢視我的前一篇文章

union semun

;#endif

void my_err(char *);

int semphore_p(int);

int semphore_v(int);

int main(void)

void my_err(char *str)

int semphore_p(int semid)

int semphore_v(int semid)

client.c 

#include #include #include #include #include #include #define ipckey 0x19890319

#ifdef _sem_semun_undefined

union semun

;#endif

void my_err(char *);

int semphore_p(int);

int semphore_v(int);

int main(void)

void my_err(char *str)

int semphore_p(int semid)

int semphore_v(int semid)

CreateFileMapping 共享記憶體

handle hfile,dword flprotect,dword dwmaximumsizehigh,dword dwmaximumsizelow,lpctstr lpname hfile 共享檔案控制代碼,不建立共享檔案,為invalid handle value flprotect 保護選項...

Linux高階程式設計基礎 程序間通訊之共享記憶體

建立共享記憶體,寫程序每隔2秒向記憶體寫入一次 hello world 如果結束寫操作,則寫程序寫入 end 讀程序從共享記憶體讀取資料,並列印。直到讀到 end 為止。這是寫程序 include include include include include include include inc...

4 執行緒範圍內的資料共享之ThreadLocal

1 2 執行緒範圍類的資料共享 3 核心 threadlocal類 4 實際場景 5 hibernate的getcurrentsession方法,就是從執行緒範圍內獲取存在的session,如果不存在則新建乙個並繫結到執行緒上 6 struts將乙個請求裡的所有引數繫結到乙個執行緒範圍內的物件裡7 ...