下面兩支小程式示範 System V 消息隊列最基本的用法:一支負責阻塞發送,一支負責阻塞讀取。兩者透過 ftok() 產生的同一個 key 找到同一個隊列。
/*msg_block_read.c*/
#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct msg_buf
{
int mtype;
// char aaa[255]; // 此結構體只能包含兩個成員
char data[255];
};
int main()
{
key_t key;
int msgid;
int ret;
struct msg_buf msgbuf;
key = ftok("/tmp/2", 'a');
printf("key =[%x]\n", key);
msgid = msgget(key, IPC_CREAT | 0666); /* 透過檔案對應 */
if (msgid == -1)
{
printf("create error\n");
return -1;
}
/*
msgbuf.mtype = getpid();
strcpy(msgbuf.data, "test haha, aaaaaaaaaaaaaaaaaa");
ret = msgsnd(msgid, &msgbuf, strlen(msgbuf.data), 0);
if (ret == -1)
{
printf("send message err\n");
return -1;
}
*/
memset(&msgbuf, 0, sizeof(msgbuf));
ret = msgrcv(msgid, &msgbuf, sizeof(msgbuf.data), 0, 0); // 阻塞讀取第一則訊息
if (ret == -1)
{
printf("recv message err\n");
return -1;
}
printf("recv msg =[%s], len = %d\n", msgbuf.data, strlen(msgbuf.data));
return 0;
}
/*msg_block_write.c*/
#include <sys/types.h>
#include <sys/msg.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct msg_buf
{
int mtype;
// char aaa[255]; // 此結構體只能包含兩個成員
char data[255];
};
int main()
{
key_t key;
int msgid;
int ret;
struct msg_buf msgbuf;
key = ftok("/tmp/2", 'a');
printf("key =[%x]\n", key);
msgid = msgget(key, IPC_CREAT | 0666); /* 透過檔案對應 */
if (msgid == -1)
{
printf("create error\n");
return -1;
}
msgbuf.mtype = getpid();
strcpy(msgbuf.data, "test haha, aaaaaaaaaaaaaaaaaa");
ret = msgsnd(msgid, &msgbuf, strlen(msgbuf.data), 0); // 阻塞發送
if (ret == -1)
{
printf("send message err\n");
return -1;
}
/*
memset(&msgbuf, 0, sizeof(msgbuf));
ret = msgrcv(msgid, &msgbuf, sizeof(msgbuf.data), getpid(), 0);
if (ret == -1)
{
printf("recv message err\n");
return -1;
}
printf("recv msg =[%s], len = %d\n", msgbuf.data, strlen(msgbuf.data));
*/
return 0;
}
結構體的第一個成員必須是 long mtype(這裡寫成 int,在 64 位元平台上嚴格來說不符合標準,long 與 int 寬度不同會造成 msgsnd/msgrcv 的偏移錯位,正式使用前請改成 long mtype;)。訊息本文由第二個成員開始,程式碼中的註解「只能包含兩個成員」講的就是這個約束。
msgsnd 的第三個參數是「本文長度」,不含 mtype,所以傳的是 strlen(msgbuf.data) 而非整個結構體大小;msgrcv 的 msgtyp 傳 0 代表「取第一則不論型別」,若傳 >0 則只取該型別,<0 則取型別小於或等於其絕對值的最小值。
兩支程式都沒呼叫 msgctl(msgid, IPC_RMID, NULL),所以隊列會殘留在系統中。測試完記得手動清掉,可用 ipcs -q 查詢再 ipcrm -q <id> 移除,否則 key 不變的情況下重複測試會一直讀到舊訊息。
另外 ftok("/tmp/2", 'a') 要求該路徑存在,否則回傳 -1;這也是初學時「key 怎麼算都不對」的常見原因。