Linux C程式設計 訊息佇列實現同時通訊

2021-07-24 01:44:24 字數 2660 閱讀 6583

訊息佇列實現同時通訊

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

訊息佇列就是乙個訊息的鍊錶.可以把訊息看作乙個記錄,具有特定的格式.程序可以向中按照一定的規則新增新訊息;另一些程序則可以從訊息佇列中讀走訊息

首先,我們可以利用訊息佇列實現通訊,注意,此時只能乙個寫乙個發,下面是例程,大家可以嘗試一下:

msg1.c  接收訊息

#include #include #include #include #include #include #include #include struct my_msg_st; 

int main(void)

/*迴圈從訊息佇列中接收訊息*/

while(running)

printf("you wrote: %s",some_data.some_text);

/*接收到的訊息為「end」時結束迴圈*/

if(strncmp(some_data.some_text,"end",3)==0)}

/*從系統核心中移走訊息佇列*/

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

exit(exit_success);

}

msg2.c 傳送訊息

#include #include #include #include #include #include #include #include #define max_text 512

struct my_msg_st;

int main(void)

/*迴圈向訊息佇列中新增訊息*/

while(running)

/*使用者輸入的為「end」時結束迴圈*/

if(strncmp(buffer,"end",3)==0)

}exit(exit_success);

}

但是我們怎麼才能實現兩端同時通訊,可以同時讀寫呢?此時,我們應考慮到父子程序,在msg1.c 中,我們設定父程序進行傳送,子程序進行接收,而在msg2.c中,我們設定子程序進行傳送,父程序進行接收。

下面是我自己的實現,大家可以試一下,如有錯誤歡迎指正~

msg1.c :

#include #include #include #include #include #include #include #include #define max_text 512

struct my_msg_st;

int main(void)

/*建立訊息佇列*/

msgid = msgget((key_t)1234,0666|ipc_creat);

if(msgid == -1)

if(pid == 0) //子程序

printf("%s",some_data.some_text);

/*接收到的訊息為「end」時結束迴圈*/

if(strncmp(some_data.some_text,"end",3) == 0)}}

else if(pid > 0) //父程序

if(strncmp(some_data.some_text,"end",3) == 0)}}

/*從系統核心中移走訊息佇列*/

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

exit(exit_success);

}

msg2.c

#include #include #include #include #include #include #include #include #define max_text 512

struct my_msg_st;

int main(void)

/*建立訊息佇列*/

msgid = msgget((key_t)1234,0666|ipc_creat);

if(msgid == -1)

if(pid == 0) //子程序

/*使用者輸入的為「end」時結束迴圈*/

if(strncmp(some_data.some_text,"end",3) == 0)}}

else if(pid > 0) //父程序

printf("%s",some_data.some_text);

if(strncmp(some_data.some_text,"end",3) == 0)}}

exit(exit_success);

return 0;

}

linux c 迴圈訊息佇列寫法

很多場合,我們需要乙個迴圈訊息處理模式,乙個執行緒產生訊息,乙個執行緒進行處理。產生訊息的執行緒就不用阻塞了,可以用了幹其他的事情了。常見串列埠或者網路通訊,負責解析位元組流的執行緒將訊息初步解析然後放置到乙個訊息佇列裡面,處理執行緒負責迴圈取出訊息佇列裡面的訊息進行相應的動作。下面是一在liunx...

Linux C 訊息佇列實現簡單的聊天功能

訊息佇列是提供一種帶有資料標識的特殊管道,使得每一段被寫入的資料都變成帶標識的訊息,讀取該段訊息的程序只要指定這個標識就可以正確地讀取,而不會受到其他訊息的干擾,乙個帶標識的訊息佇列,就像並存的管道一樣。這裡主要介紹的是利用執行緒和訊息佇列,寫兩個程序,實現兩個程序之間的聊天功能。使用方法 傳送者 ...

linux C 程序間通訊 訊息佇列

linux 引入訊息佇列的原因是,實現對緊急事件的處理。可以為訊息設定優先順序 下面是乙個共享訊息佇列的例子,在linux2.6的核心中能夠執行,通過訊息佇列實現程序間的通訊,可以自己選擇優先順序,本列優先順序設定為子程序自己的pid.2.6中能夠執行,include include include...