歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 一步一步學Linux C:消息隊列實例

一步一步學Linux C:消息隊列實例

日期:2017/3/1 10:26:04   编辑:Linux編程

消息隊列是一系列連續排列的消息,保存在內核中,通過消息隊列的引用標識符來訪問。消息隊列與管道很相似,但使用消息隊列的好處是對每個消息指定了特定消息類型,接收消息的進程可以請求接收下一條消息,也可以請求接收下一條特定類型的消息。

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