在linux核心中建立一段共享記憶體,使用shmget函式:
#include
#include
int shmget(key_t key, size_t size, int shm***);
第乙個引數key定義是否建立乙個帶金鑰的共享記憶體。
shmat:將共享記憶體對映到使用者空間.include
#include
#include
#include
#include
#include
int main()
printf
("creat key sucess key=%x\n"
,key)
; shmid=
shmget
(key,
128,
ipc_creat
|0777);
if(shmid<0)
printf
("creat share memory sucess shmid=%d\n"
,shmid)
;system
("ipcs -m");
system
("ipcrm -m shmid");
return0;
}
void *shmat(int shmid, const void *shmaddr, int shm***);
返回值為指標型別,指向使用者空間的某個位址,該位址可通過shmaddr變數進行設定。若由記憶體自行分配,可以設定為null
shmdt:將使用者空間的對映記憶體刪除
int shmdt(const void *shmaddr);
shmctl:對用核心空間的共享記憶體進行操作
1、讀取物件屬性
2、設定物件屬性
3、刪除物件屬性
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
對共享記憶體的總結:#include
#include
#include
#include
#include
#include
#include
int main()
printf
("creat key sucess key=%x\n"
,key)
; shmid=
shmget
(key,
128,
ipc_creat
|0777);
if(shmid<0)
printf
("creat share memory sucess shmid=%d\n"
,shmid)
;system
("ipcs -m");
p=(char *
)shmat
(shmid,
null,0
);if(p==
null
)fgets
(p,128
,stdin)
;printf
("share memory data:%s"
,p);
shmdt
(p);
// memcmp(p,"abcd",4);
shmctl
(shmid,
ipc_rmid
,null);
system
("ipcs -m");
return0;
}
對共享記憶體的實現步驟:首先要建立記憶體空間,將記憶體空間對映到使用者空間,使用標準輸入輸出函式對記憶體內容進行讀取,(共享記憶體可分為有血緣關係的使用者程序和無血緣關係的使用者程序,這裡可以通過是否選擇ftok建立key值)然後是刪除共享記憶體空間。
##訊息佇列
在linux核心中通過msgget開啟或建立佇列。
#include
#include
#include
int msgget(key_t key, int msg***);
通過msgsnd和msgrcv函式來佇列傳送資訊或從核心接收資訊
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msg***);
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msg***);
下列**是實現佇列的雙向通訊
a程序
b程序#include
#include
#include
#include
#include
#include
#include
struct msgbuf
;int main()
msgid=
msgget
(key,
ipc_creat
|0777);
if(msgid<0)
printf
("creat message queue sucess:msgid=%d\n"
,msgid)
;system
("ipcs -q");
pid=
fork()
;if(pid==0)
//}if(pid>0)
}//刪除訊息佇列
msgctl
(msgid,
ipc_rmid
,null);
system
("ipcs -q");
return0;
}
結構體中long欄位必須具有嚴格的正整數值。 接收過程可以使用此值進行訊息選擇。#include
#include
#include
#include
#include
#include
#include
struct msgbuf
;int main()
msgid=
msgget
(key,
ipc_creat
|0777);
if(msgid<0)
printf
("creat message queue sucess:msgid=%d\n"
,msgid)
;system
("ipcs -q");
pid=
fork()
;if(pid>0)
//}if(pid==0)
}/* system("ipcs -q");
memset(revbuf.voltage,0,128);
readret=msgrcv(msgid,(void *)&revbuf,128,100,0);
printf("revbuf.voltage=%s\n",revbuf.voltage);
*///刪除訊息佇列
msgctl
(msgid,
ipc_rmid
,null);
system
("ipcs -q");
return0;
}
Linux程序間通訊(二) 共享記憶體 訊息佇列
一 共享記憶體 最高效的程序間通訊機制。多個程序共享一段記憶體。需要依靠某種同步機制,如互斥鎖或訊號量。通常步驟為 建立 對映 使用 撤銷對映 刪除 相關函式可以參考 linux 共享記憶體 include include include include include include semcom...
Linux程序間通訊(二) 共享記憶體 訊息佇列
一 共享記憶體 最高效的程序間通訊機制。多個程序共享一段記憶體。需要依靠某種同步機制,如互斥鎖或訊號量。通常步驟為 建立 對映 使用 撤銷對映 刪除 相關函式可以參考 linux 共享記憶體 include include include include include include semcom...
Linux 記憶體共享與訊息佇列
共享記憶體 共享共存區域是被多個程序共享的一部分物理記憶體。如果多個程序都 把該記憶體區域對映到自己的虛擬位址空間,則這些程序就都可以直接 訪問該共享記憶體區域,從而可以通過該區域進行通訊。共享記憶體是進 程間共享資料的一種最快的方法,乙個程序向共享記憶體區域寫入了數 據,共享這個記憶體區域的所有程...