一步一步学Linux C:消息队列实例


消息队列是一系列连续排列的消息,保存在内核中,通过消息队列的引用标识符来访问。消息队列与管道很相似,但使用消息队列的好处是对每个消息指定了特定消息类型,接收消息的进程可以请求接收下一条消息,也可以请求接收下一条特定类型的消息。

  1. #include <sys/types.h>   
  2. #include <sys/ipc.h>   
  3. #include <sys/msg.h>   
  4. #include <stdio.h>   
  5. #include <string.h>   
  6.   
  7. int main()  
  8. {  
  9.     key_t unique_key;  
  10.     int msgid;  
  11.       
  12.     int status;  
  13.     char str1[]={"test message:hello muge0913"};  
  14.     char str2[]={"test message:goodbye muge0913"};  
  15.       
  16.     struct msgbuf  
  17.     {  
  18.     long msgtype;  
  19.     char msgtext[1024];  
  20.     }sndmsg,rcvmsg;  
  21.   
  22.     if((msgid = msgget(IPC_PRIVATE,0666))==-1)  
  23.     {  
  24.     printf("msgget error!\n");  
  25.     exit(1);  
  26.     }  
  27.   
  28.     sndmsg.msgtype =111;  
  29.     sprintf(sndmsg.msgtext,str1);  
  30.   
  31.     if(msgsnd(msgid,(struct msgbuf *)&sndmsg,sizeof(str1)+1,0)==-1)  
  32.     {  
  33.     printf("msgsnd error!\n");  
  34.     exit(1);  
  35.     }  
  36.   
  37.     sndmsg.msgtype =222;  
  38.     sprintf(sndmsg.msgtext,str2);  
  39.     if(msgsnd(msgid,(struct msgbuf *)&sndmsg,sizeof(str2)+1,0)==-1)  
  40.     {  
  41.     printf("msgsnd error\n");  
  42.     exit(1);  
  43.     }  
  44.   
  45.     if((status = msgrcv(msgid,(struct msgbuf *)&rcvmsg,80,222,IPC_NOWAIT))==-1)  
  46.     {  
  47.     printf("msgrcv error\n");  
  48.     exit(1);  
  49.     }  
  50.   
  51.     printf("The receved message:%s\n",rcvmsg.msgtext);  
  52.     msgctl(msgid,IPC_RMID,0);  
  53.     exit(0);  
  54. }  
一步一步学Linux C:消息队列实例

相关内容