一步一步学Linux C:消息队列实例
一步一步学Linux C:消息队列实例
消息队列是一系列连续排列的消息,保存在内核中,通过消息队列的引用标识符来访问。消息队列与管道很相似,但使用消息队列的好处是对每个消息指定了特定消息类型,接收消息的进程可以请求接收下一条消息,也可以请求接收下一条特定类型的消息。
- #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);
- }
评论暂时关闭