Linux下程序間通訊 訊息佇列詳解

2021-08-06 06:31:00 字數 1940 閱讀 2633

訊息佇列

(1)概念:

unix早期通訊機制之一的訊號能夠傳送的資訊量有限,管道則只能傳送無格式的位元組流,這無疑會給應用程式開發帶來不便。訊息佇列(也叫做報文佇列)則克服了這些缺點。

訊息佇列就是乙個訊息的鍊錶。可以把訊息看作乙個記錄,具有特定的格式。

程序可以向其中按照一定的規則新增新訊息;另一些程序則可以從訊息佇列中讀走訊息。

訊息佇列分兩種:

posix訊息佇列以及系統v訊息佇列 系統v訊息佇列目前被大量使用

(2)建立

int msgget(key_t key, int msg***)
引數解釋:

key: 鍵值,由fork獲得

msg***:標誌位

msg***取值:

ipc_creat

建立新的訊息佇列

ipc_excl

與ipc_creat一同使用,表示如果要建立的訊息佇列已經存在,則返回錯誤。

ipc_nowait

讀寫訊息佇列要求無法得到滿足時,不阻塞。

在以下兩種情況下,將建立乙個新的訊息佇列:

如果沒有與鍵值key相對應的訊息佇列(也就是不能重複),並且msg***中包含了ipc_creat標誌位。

(3)傳送訊息

int msgsnd(int msqid, struct msgbuf * msgp, int msgsz, int msg***)
功能:向訊息佇列中傳送一條訊息

msqid:訊息佇列描述符

msgp:訊息佇列指標,指向存放訊息的結構

msgsz:訊息資料長度

msg***:傳送標誌,有意義的msg***標誌為ipc_nowait,指明在訊息佇列沒有足夠空間容納要傳送的訊息時,msgsnd是否等待

訊息格式:

struct msgbuf

(4)接受訊息

int msgrcv(int msqid, struct msgbuf* msgp, int msgsz, long msgtp, int msg***)
功能:從msqid代表的訊息佇列中讀取乙個msgtyp型別的訊息,並把訊息儲存在msgp指向的msgbuf結構中。在成功的讀取了一條訊息以後,佇列中的這條訊息將被刪除。

傳送訊息佇列**:

#include #include #include #include #include struct msgbuf; 

int main()

//訊息寫入;

struct msgbuf msg;

msg.mtype = 2;

strcpy(msg.mtext ,"hello");

//傳送訊息佇列;

int ret = msgsnd (msgid, &msg, 100, ipc_nowait);

if(ret == -1)

return 0;

}

接受訊息佇列**:

#include #include #include #include #include struct msgbuf; 

int main()

struct msgbuf msg;

//接受訊息佇列;

int ret = msgrcv (msgid, &msg, 100, 2,ipc_nowait);

if(ret == -1)

printf("%s\n",msg.mtext);

return 0;

}

注意!

在執行這兩個程式之後,我把傳送訊息端的程式關閉,編譯執行讀端的程式,是什麼也讀不出來的!就是上面說過,當讀取結束之後訊息佇列裡邊的訊息就已經被刪除,資料是一次性的;

Linux系統下 程序間通訊(訊息佇列)

linux系統下 程序間通訊 訊息佇列 詳解 send.c include include include include include define msgkey 123 訊息的資料結構是以乙個長整型成員變數開始的結構體 struct msgstru void main while 1 刪除訊息...

Linux程序間通訊 訊息佇列

linux和類linux系統下程序間通訊 inter process communication,ipc 有很多種方式,包括套接字 socket 共享記憶體 shared memory 管道 pipe 訊息佇列 message queue 等,各自有各自的一些應用場景和用途,這次就來聊一聊訊息佇列這...

linux程序間通訊 訊息佇列

訊息佇列由id 唯一標識 訊息佇列就是乙個訊息的列表,使用者可在佇列中新增,讀取訊息等 可按照型別來收發訊息 int msgget key t key,int flag int msgsnd int msqid,const void msgp,size t size,int flag msqid 訊...