消息隊列見習

1,消息隊列從本質上講就是一個鏈表,一個消息的鏈表。

2,消息隊列通信主要步驟:

(1),通過ftok()獲取一個鍵值;

(2),通過這個鍵值創建一個消息隊列,並將消息隊列與鍵值相關聯。通過message get:msgget( )函數來創建。

(3),操作消息隊列:發送消息,message send:msgsnd()與接收消息,receive message:msgrcv().

(4),刪除消息隊列:msgctl().

3,創建消息隊列

# include <sys/types.h>

# include <sys/ipc.h>

# include <sys/msg.h>

int msgget(key_t key, int msgflg);

msgflg,操作與權限,IPC_CREAT | 0666

4,發送消息,msgsnd()

# include <sys/types.h>

# include <sys/ipc.h>

# include <sys/msg.h>

int msgsnd(int msqid, struct msgbuf *msgp, size_t msgsz, int msgflg);

(1)msqid是msgget()函數返回的消息隊列描述符,表示你要把消息隊列發送到哪個消息隊列裏面去。

(2)msgp是一個指向struct msgbuf 型結構體的指針,表示你要把發送的消息存放到哪種類型的結構體變量中。固定格式的

struct msgbuf

{

long mtype;//消息類型,必須大於0;

char mtext[消息長度];//消息內容

};

(3),msgsz:表示要發送或接收的消息的字節數,即msgbuf中存放消息的mtext數組的長度,通過sizeof即可獲得。

(4),msgflg:折個參數依然是控制函數行爲的標誌。

5,接收消息:

# include <sys/types.h>

# include <sys/ipc.h>

# include <sys/msg.h>

ssize_t msgrcv(int msqid, struct msgbuf *msgp, size_t msgsz, long msgtyp, int msgflg);

6,刪除消息隊列:msgctl()

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/msg.h>

int msgctl(int msqid, int cmd, struct msqid_ds *buf);

① 參數shmid表示要控制的是哪個消息隊列,即msgget()函數的返回值;

② 參數cmd如果取IPC_RMID就表示刪除消息隊列,即remove ID。我們一般使用shmctl()函數就是刪除消息隊列,所以cmd一般都取IPC_RMID,其它參數我們就不看了。PC_RMID的宏值爲0,我們在編程的時候可以寫宏名也可以直接寫宏值,這裏直接寫宏值好像更方便一點,但含義沒有宏名直觀。

③ 參數struct msqid_ds *是一個結構體指針,同樣這個參數一般就寫NULL。

 

舉例:

# include <unistd.h>

# include <sys/types.h>

# include <sys/ipc.h>ls

 

# include <sys/msg.h>

# include <stdlib.h>

# include <stdio.h>

# include <string.h>

 

struct msgbuf

{

long mtype;  /*消息類型,必須大於0 */

char mtext[1024];    /*消息內容*/

};

 

int main(void)

{

//獲取鍵值

int key = ftok(".", 1);

 

//創建消息隊列

int msgid = msgget(key, IPC_CREAT | 0666);

 

//發送消息

struct msgbuf data;

 

data.mtype = 3;

strcpy(data.mtext, "i love you");

 

msgsnd(msgid, &data, 1024, 0);

 

return 0;

}

 

# include <unistd.h>

# include <sys/types.h>

# include <sys/ipc.h>

# include <sys/msg.h>

# include <stdlib.h>

# include <stdio.h>

# include <string.h>

 

struct msgbuf

{

long mtype;  /*消息類型,必須大於0 */

char mtext[1024];    /*消息內容*/

};

 

int main(void)

{

//獲取鍵值

int key = ftok(".", 1);

 

//打開消息隊列

int msgid = msgget(key, IPC_CREAT);

 

//接收消息

struct msgbuf data;

 

msgrcv(msgid, &data, 1024, 3, 0);

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

 

//刪除消息隊列

msgctl(msgid, 0, NULL);

 

return 0;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章