sys/types.h、sys/ipc.h、sys/msg.h#include
#include
#include
#include
#include
struct msgbuf {
long msgtype; // 消息類型(必須 > 0)
char msgtext[1024]; // 消息內容
};
int main() {
key_t unique_key;
int msgid;
int status;
char str1[] = "test message:hello muge0913";
char str2[] = "test message:goodbye muge0913";
struct msgbuf sndmsg, rcvmsg;
// 創建私有隊列
if ((msgid = msgget(IPC_PRIVATE, 0666)) == -1) {
perror("msgget"); exit(1);
}
// 發送類型 111
sndmsg.msgtype = 111;
sprintf(sndmsg.msgtext, "%s", str1);
if (msgsnd(msgid, &sndmsg, sizeof(str1)+1, 0) == -1) {
perror("msgsnd"); exit(1);
}
// 發送類型 222
sndmsg.msgtype = 222;
sprintf(sndmsg.msgtext, "%s", str2);
if (msgsnd(msgid, &sndmsg, sizeof(str2)+1, 0) == -1) {
perror("msgsnd"); exit(1);
}
// 非阻塞接收類型 222
if ((status = msgrcv(msgid, &rcvmsg, 80, 222, IPC_NOWAIT)) == -1) {
perror("msgrcv"); exit(1);
}
printf("The received message: %s\n", rcvmsg.msgtext);
// 刪除隊列
msgctl(msgid, IPC_RMID, 0);
return 0;
}

輸出:The received message: test message:goodbye muge0913
| 函數 | 作用 |
|---|---|
| msgget(key, flags) | 創建/獲取隊列,返回標識符 |
| msgsnd(msqid, msgp, msgsz, flag) | 發送消息,flag=0 阻塞,IPC_NOWAIT 非阻塞 |
| msgrcv(msqid, msgp, msgsz, msgtyp, flag) | 接收消息,msgtyp=0 取首條,>0 取指定類型,<0 取類型≤|msgtyp| 首條 |
| msgctl(msqid, cmd, buf) | 控制:IPC_RMID 刪除,IPC_STAT/SET 狀態讀寫 |
long msgtype 必須為正數sizeof(str)+1 含結束符