訊息佇列與 FIFO 相似,但多了隨機查詢的能力——接收端可以依訊息型別挑著讀,而不必嚴格照順序。核心操作只有四個函式:msgget、msgsnd、msgrcv、msgctl。
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 512
struct message { long msg_type; char msg_text[BUFFER_SIZE]; };
int main()
{
int qid;
key_t key;
struct message msg;
if ((key = ftok(".", 'a')) == -1) { perror("ftok"); exit(1); }
if ((qid = msgget(key, IPC_CREAT|0666)) == -1) { perror("msgget"); exit(1); }
printf("open queue %d\n", qid);
while (1) {
printf("enter some message to the queue:");
if (fgets(msg.msg_text, BUFFER_SIZE, stdin) == NULL) { puts("no message"); exit(1); }
msg.msg_type = getpid(); /* 型別用行程號 */
if (msgsnd(qid, &msg, strlen(msg.msg_text), 0) < 0) { perror("message posted"); exit(1); }
if (strncmp(msg.msg_text, "quit", 4) == 0) break;
}
exit(0);
}#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define BUFFER_SIZE 512
struct message { long msg_type; char msg_text[BUFFER_SIZE]; };
int main()
{
int qid;
key_t key;
struct message msg;
if ((key = ftok(".", 'a')) == -1) { perror("ftok"); exit(1); }
if ((qid = msgget(key, IPC_CREAT|0666)) == -1) { perror("msgget"); exit(1); }
printf("open queue %d\n", qid);
do {
memset(msg.msg_text, 0, BUFFER_SIZE);
if (msgrcv(qid, (void*)&msg, BUFFER_SIZE, 0, 0) < 0) { perror("msgrcv"); exit(1); }
printf("the message from process %d : %s", msg.msg_type, msg.msg_text);
} while (strncmp(msg.msg_text, "quit", 4));
if (msgctl(qid, IPC_RMID, NULL) < 0) { perror("msgctl"); exit(1); }
exit(0);
}開兩個終端,一號發送、二號接收。關鍵細節:ftok 依路徑與專案字元產生標準 key,兩端必須一致;msg_type 必須是正長整數,這裡用行程號;msgrcv 第五個參數 0 代表不限型別,改成特定值即可做選擇性接收,這正是它勝過管道之處。最後 msgctl 的 IPC_RMID 負責把佇列從核心移除,否則會殘留,可用 ipcs -q 檢查、ipcrm -q <id> 清除。