程序間通訊(二) 訊息佇列

2021-08-20 04:53:03 字數 2547 閱讀 9651

訊息佇列是作業系統為兩個無關程序準備的通訊方式,每個訊息佇列都有乙個他自己的id我們用來標識訊息佇列

訊息佇列的不足就是我們傳送訊息的

最大長度有限制,並且作業系統提供的

訊息佇列的個數也是有限的

此id用如下函式建立

此函式中的path為乙個路徑,講道理這個路徑其實可以隨便定義,一般定義成當前目錄即可,然後這個proj_id就是乙個數字而已可以隨便設,啊就是這樣,但是我們要知道同乙個路徑同乙個專案id數完全有可能產生同乙個訊息佇列id的,並且我們要注意的是訊息佇列和管道不一樣,管道的生命隨程序,但是訊息佇列的生命隨作業系統,所以當我們建立了乙個新的訊息佇列的話一定要手動的去銷毀,不然再次建立的話就有可能會失敗,那麼這我們介紹兩個命令

ipcs -q:檢視所有的訊息佇列

ipcrm -q id:刪除id的訊息佇列

那現在我們知道建立訊息佇列失敗的原因:

作業系統的訊息佇列的數目已達上限

建立的此訊息佇列的id已被占用

那我們用訊息佇列來寫乙個

伺服器和客戶端的相互通訊

首先是關於訊息佇列的一系列的函式

comm.h

#ifndef _comm_h_

#define _comm_h_

#include

#include

#include

#include

#include

#define path_name "/tmp"

#define proj_id 0x6666

//建立訊息佇列

#define server_type 1

#define client_type 2

//此時我們用msgbuf是顯示重定義

//應該是在標頭檔案裡的msg緩衝區定義為msgbuf

//我們將我們的名字換一下即可

struct msgbuff ;

int createmsgqueue();

//建立訊息佇列

int getmsgqueue();

//獲得訊息佇列

int sendmsg(int msgid,char *msg,int t);

//傳送訊息佇列

//接受訊息佇列

int recvmsg(int msgid,char *msg,int t);

//銷毀訊息佇列

void destorymsgqueue(int msgid);

#endif

comm.c

#include "comm.h"

int commmsgqueue(int flag)

int msgid = msgget(k,flag);

if(msgid < 0)

return msgid; }

int createmsgqueue()

int getmsgqueue()

void  destorymsgqueue(int msgid)

} //傳送資料塊

//msgid(訊息佇列的識別符號),msg(資料塊結構體的位址),

//msgsz(資料塊裡陣列的位元組大小),msg***(判斷是阻塞式還是非阻塞式)

//int msgsnd(int msqid, const void *msgp, size_t msgsz, int msg***);

int sendmsg(int msgid,char *msg,int t)

return 0; }

//接收資料塊

//msgtyp(資料塊內容的型別)

//ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msg***);

//msg:要傳送的資料

int recvmsg(int msgid,char *msg,int t)

strcpy(msg,buf.mtext);

return 0; }

接下來是我們的伺服器和客戶端的**

因為伺服器端是先接受訊息,再傳送訊息

#include"comm.h"

int main()

recvmsg(msgid,buf,client_type);

printf("client #%s\n",buf);

printf("please enter:");

scanf("%s",buf);

sendmsg(msgid,buf,server_type); }

destorymsgqueue(msgid);

return 0; }

客戶端是先傳送訊息再接收訊息

#include"comm.h"

int main()

recvmsg(msgid,buf,server_type);

printf("server #%s\n",buf); }

destorymsgqueue(msgid);

return 0; }

程序間通訊 訊息佇列(二)

例項 模擬經緯度的收發工作。採用訊息佇列的方式處理 專案中涉及2個不相關程序a和程序b 假設你是專案的程序a編寫者,你負責把程序a的經緯度傳送到 第三方導航軟體中 導航定位 程序b 程序a每2秒傳送一次經緯度,程序b每3秒接受一次經緯度並列印顯示。上海預設是北緯東經 資料體 body 協議 int ...

程序間通訊(二) 訊息佇列

我會用幾篇部落格總結一下在linux中程序之間通訊的幾種方法,我會把這個開頭的摘要部分在這個系列的每篇部落格中都打出來 程序之間通訊的方式 程序間通訊 一 管道傳送門 程序間通訊 三 訊號量傳送門 程序間通訊 四 共享儲存區傳送門 程序間通訊 五 訊號傳送門 這次主要寫的是訊息佇列,之前講過的管道和...

程序間訊息佇列通訊

要保證server能夠接收client的訊息,就必須保證server的生成的msg的識別符號是一樣的,也就是兩個用的key是必須一樣的。msglucy.c include include include include include include include include include ...