共享記憶體是允許多個程序共享記憶體;
共享記憶體結構
struct shmid_ds
struc ipc_permshm_perm;//指向該記憶體指標
int shm_segsz;//共享記憶體的大小
ushort
shm_lkcnt;//共享記憶體被鎖定的時間
pid_t
shm_cpid;//最近呼叫shompde程序的程序號
pid_t
shm_lpid;//建立該共享記憶體程序的程序號
ulong
shm_nattach;//當前把該記憶體段附加到位址空間的程序數
time_t
shm_atime;//最新附加操作時間
time_t
shm_dtime;//最新分離時間
time_t
shm_ctime;//最新改變時間
需要的庫
#include
#include
#include
共享記憶體建立與開啟
int shmget(key_t key, int size, int flag);
key關鍵字;
size記憶體大小
flag操作型別
當key = ipc_private; flag任何值時,建立新記憶體。
當key != ipc_private;
flag = ipc_create
時,開啟已有共享記憶體;否則,建立新記憶體。
當key != ipc_private;
flag = ipc_create | ipc_excl時
,開啟已有共享記憶體,否則失敗;
共享記憶體操作
void* shmat(int shmid ,void *addr, int flag);
當addr= 0;
flag 任何值
時,將共享記憶體附加到第一塊有效記憶體區域。
當addr != 0;
flag !=shm_rnd
時,將共享記憶體附加到addr指向記憶體位址。
當addr != 0;
flag !=shm_rnd
時,將共享記憶體附加到addr-(addr%shmlba)指向記憶體位址。
共享記憶體操作
int shmctl(int shmid, int cmd, shmid_ds *buf);
cmd的取值與對應操作
shm_lock由超級使用者上鎖
ipc_rmid刪除共享記憶體
ipc_set按引數buf指向結構中的值設定該共享記憶體對應的shmid_ds結構
ipc_stat取出shmid_ds結構,並儲存到buf所指向的緩衝區
shm_unlock由超級使用者解鎖
舉例:在服務端建立共享記憶體,然後在客戶端讀取
#include #include #include #include #include #include int main()
if((shmptr = shmat(shmid, 0 ,0))==-1)
s = shmptr;
for(c = 'a'; c<= 'z';c++)
*s++ = c;
*s = null;
while(*shmptr!='*')
sleep(1);
shmctl(shmid, ipc_rmid, shmptr);
return 0;
}
#include #include #include #include #include int main()
if((shmptr = shmat(shmid, 0, 0))<0)
for(s = shmptr; *s!=null; s++)
; printf("\n");
*shmptr='*';
return 0;
}
程序通訊 共享記憶體
定義 共享記憶體,就是通過核心操作,在記憶體上開闢一塊供多個程序共同訪問的記憶體塊。這塊記憶體塊的建立和 銷毀是由核心來控制 當然,也可以在程序內部呼叫系統庫函式來建立和銷毀,類似於訊息機制和訊號 量機制 在這個記憶體塊上,程序可以像操作記憶體一樣操作共享區記憶體。作用 第乙個,就是提供程序間大資訊...
程序間通訊 共享記憶體
下面是自己寫的乙個簡單的共享記憶體的程序間通訊的例子。共享記憶體是用於程序間大量資料共享的一種方法。include include include include include include int main if buf1 shmat shmid,0,0 void 1 strcpy buf1,...
程序間通訊 共享記憶體
共享記憶體是被多個程序共享的一部分物理記憶體。共享記憶體是程序間共享資料的一種最快的方式,乙個程序向共享記憶體區域寫入資料,共享這個記憶體區域的所有程序就可以立刻看到其中的內容。共享記憶體實現分兩個步驟 建立共享記憶體,使用shmget函式 對映共享記憶體,使用shmat函式 共享記憶體是一種最為高...