程序間通訊 共享記憶體 互斥鎖同步(一)

2021-09-27 12:51:07 字數 1553 閱讀 2050

**參考網上其他人的,分三個檔案

sm_common.h

#ifndef __sm_common_h__

#define __sm_common_h__

#include #define sm_buf_size 1024

#define sm_id 0x1122

struct sm_msg;

#endif

sm_server.c

#include #include #include #include #include #include "sm_common.h"

int main(void)

shared_memory = shmat(shm_id, null, 0);

if (shared_memory == null)

msg = (struct sm_msg *)shared_memory;

msg->flag = 0;

pthread_mutex_init(&msg->sm_mutex, &attr);

while (running)

}else

}ret = shmdt(shared_memory);//disconnect shared memory

if (ret < 0)

if(shmctl(shm_id, ipc_rmid, 0) < 0)//ctrol shared memory ,rm

return 0;

}

sm_client.c

#include #include #include #include #include #include "sm_common.h"

int main(void)

shared_memory = shmat(shm_id, null, 0);//共享記憶體分配位址

if (shared_memory == null)

msg = (struct sm_msg *)shared_memory;//轉化為結構體,並把指標位址賦值給結構體指標

char buf[32];

while (running)

else

pthread_mutex_unlock(&msg->sm_mutex);//unlock

} }ret = shmdt(shared_memory);//disconnect shared memory

if (ret < 0)

#if 0 //do thsi in server.

if(shmctl(shm_id, ipc_rmid, 0) < 0)

#endif

return 0;

}

1、共享記憶體是最快的ipc方式,唯一缺點是同步機制得新增,而且,讀完資料,資料還存在。

2、這個例子有個標誌位,讀完一次就不能再讀,寫完一次就不能再寫,除非已經讀過。

3、對於資料更新過多、過快機制沒有。我要寫入資料很多,一次寫不滿,分多次,一定時間後沒有人來讀,資料滿後就要清掉,繼續寫。

程序間通訊 共享記憶體

下面是自己寫的乙個簡單的共享記憶體的程序間通訊的例子。共享記憶體是用於程序間大量資料共享的一種方法。include include include include include include int main if buf1 shmat shmid,0,0 void 1 strcpy buf1,...

程序間通訊 共享記憶體

共享記憶體是被多個程序共享的一部分物理記憶體。共享記憶體是程序間共享資料的一種最快的方式,乙個程序向共享記憶體區域寫入資料,共享這個記憶體區域的所有程序就可以立刻看到其中的內容。共享記憶體實現分兩個步驟 建立共享記憶體,使用shmget函式 對映共享記憶體,使用shmat函式 共享記憶體是一種最為高...

程序間通訊 共享記憶體

共享記憶體允許兩個或更多程序共享一塊給定的儲存區,因為資料不需要在不同程序之間訪問,這是最快的一種ipc 傳輸資訊量很大,通過記憶體空間對映程序空間實現,若伺服器程序正在將資料放入共享儲存區,則在它做完這一操作之前,客戶程序不應取這些資料,通常訊號量用來實現對共享儲存訪問的同步。核心為每個共享儲存段...