消息隊列是一系列連續排列的消息,保存在內核中,通過消息隊列的引用標識符來訪問。消息隊列與管道很相似,但使用消息隊列的好處是對每個消息指定了特定消息類型,接收消息的進程可以請求接收下一條消息,也可以請求接收下一條特定類型的消息。
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
int main()
{
key_t unique_key;
int msgid;
int status;
char str1[]={"test message:hello muge0913"};
char str2[]={"test message:goodbye muge0913"};
struct msgbuf
{
long msgtype;
char msgtext[1024];
}sndmsg,rcvmsg;
if((msgid = msgget(IPC_PRIVATE,0666))==-1)
{
printf("msgget error!\n");
exit(1);
}
sndmsg.msgtype =111;
sprintf(sndmsg.msgtext,str1);
if(msgsnd(msgid,(struct msgbuf *)&sndmsg,sizeof(str1)+1,0)==-1)
{
printf("msgsnd error!\n");
exit(1);
}
sndmsg.msgtype =222;
sprintf(sndmsg.msgtext,str2);
if(msgsnd(msgid,(struct msgbuf *)&sndmsg,sizeof(str2)+1,0)==-1)
{
printf("msgsnd error\n");
exit(1);
}
if((status = msgrcv(msgid,(struct msgbuf *)&rcvmsg,80,222,IPC_NOWAIT))==-1)
{
printf("msgrcv error\n");
exit(1);
}
printf("The receved message:%s\n",rcvmsg.msgtext);
msgctl(msgid,IPC_RMID,0);
exit(0);
}
