訊息佇列傳送資料和接收資料

2021-08-08 00:24:39 字數 1500 閱讀 7105

訊息佇列(也叫做報文佇列)能夠克服早期unix通訊機制的一些缺點。作為早期unix通訊機制之一的訊號能夠傳送的資訊量有限,後來雖然posix 1003.1b在訊號的實時性方面作了拓廣,使得訊號在傳遞資訊量方面有了相當程度的改進,但是訊號這種通訊方式更像"即時"的通訊方式,它要求接受訊號的程序在某個時間範圍內對訊號做出反應,因此該訊號最多在接受訊號程序的生命週期內才有意義,訊號所傳遞的資訊是接近於隨程序持續的概念(process-persistent);管道及有名管道則是典型的隨程序持續ipc,並且,只能傳送無格式的位元組流無疑會給應用程式開發帶來不便,另外,它的緩衝區大小也受到限制。

訊息佇列就是乙個訊息的鍊錶。可以把訊息看作乙個記錄,具有特定的格式以及特定的優先順序。對訊息佇列有寫許可權的程序可以向訊息佇列中按照一定的規則新增新訊息;對訊息佇列有讀許可權的程序則可以從訊息佇列中讀走訊息。訊息佇列是隨核心持續的。

#include#include#include#include#include#include#includestruct msgbuf

;int main()

/*建立訊息佇列*/

int msgid;

if (-1 == (msgid = msgget(key, ipc_creat|0666)))

system ("ipcs -q");

/*傳送訊息*/

struct msgbuf buf;

buf.mytype = 100;

strcpy(buf.mtext,"hello world");

if (-1 == msgsnd(msgid, &buf, sizeof(buf)-sizeof(long), 0))

system("ipcs -q");

return 0;

}

#include#include#include#include#include#include#includestruct msgbuf

;int main()

/*建立訊息佇列*/

int msgid;

if (-1 == (msgid = msgget(key, ipc_creat|0666)))

system ("ipcs -q");

/*接收訊息*/

struct msgbuf buf;

int ret;

if (-1 == (ret = msgrcv(msgid, &buf, sizeof(buf) - sizeof(long),100, 0)))

printf("buf:%d %s\n ",ret, buf.mtext);

system("ipcs -q");

/*刪除訊息佇列*/

if (-1 == msgctl(msgid, ipc_rmid, null))

system("ipcs -q");

return 0;

}

訊息佇列的傳送與接收

訊息佇列的傳送與接收 include include include include include 不包含此標頭檔案,會出現 警告 隱式宣告與內建函式strcpy不相容 struct msg buf int main int argc,char argv msgbuf.mtype getpid s...

kafka 訊息傳送和接收

傳送 例項 public class kafkaproducerdemo extends thread override public void run else catch interruptedexception e catch executionexception e num try catc...

串列埠傳送和接收訊息

stm32f4開發板搭載乙個usb串列埠,2個rs232串列埠,部落格內容介紹usb串列埠和電腦通訊 步驟 1 串列埠和io口使能 rcc apb2periphclockcmd rcc apb2periph usart1,enable rcc ahb1periphclockcmd rcc ahb1p...