歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux基礎編程 消息隊列 msgsnd

Linux基礎編程 消息隊列 msgsnd

日期:2017/3/1 10:17:14   编辑:Linux編程

實際上,消息隊列常常保存在鏈表結構中。擁有權限的進程可以向消息隊列中寫入或讀取消息。

消息隊列本身是異步的,它允許接收者在消息發送很長時間後再取回消息,這和大多數通信協議是不同的。例如WWW中使用的HTTP協議是同步的,因為客戶端在發出請求後必須等待服務器回應。然而,很多情況下我們需要異步的通信協議。比如,一個進程通知另一個進程發生了一個事件,但不需要等待回應。但消息隊列的異步特點,也造成了一個缺點,就是接收者必須輪詢消息隊列,才能收到最近的消息。

和信號相比,消息隊列能夠傳遞更多的信息。與管道相比,消息隊列提供了有格式的數據,這可以減少開發人員的工作量。但消息隊列仍然有大小限制。

包含文件
1、msg.c
2、msg.h
3、thread.c

源文件1 msg.c

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/msg.h>
  5. #define __DEBUG
  6. #ifdef __DEBUG
  7. #define DBG(fmt,args...) fprintf(stdout, fmt, ##args)
  8. #else
  9. #define DBG(fmt,args...)
  10. #endif
  11. #define ERR(fmt,args...) fprintf(stderr, fmt, ##args)
  12. /*
  13. 消息隊列初始化
  14. msgKey:消息隊列鍵值
  15. qid:返回值,消息隊列id
  16. */
  17. int Msg_Init( int msgKey )
  18. {
  19. int qid;
  20. key_t key = msgKey;
  21. /*
  22. 消息隊列並非私有,因此此鍵值的消息隊列很可能在其他進程已經被創建
  23. 所以這裡嘗試打開已經被創建的消息隊列
  24. */
  25. qid = msgget(key,0);
  26. if(qid < 0){
  27. /*
  28. 打開不成功,表明未被創建
  29. 現在可以按照標准方式創建消息隊列
  30. */
  31. qid = msgget(key,IPC_CREAT|0666);
  32. DBG("Create msg queue id:%d\n",qid);
  33. }
  34. DBG("msg queue id:%d\n",qid);
  35. return qid;
  36. }
  37. /*
  38. 殺死消息隊列
  39. qid:消息隊列id
  40. */
  41. int Msg_Kill(int qid)
  42. {
  43. msgctl(qid, IPC_RMID, NULL);
  44. DBG("Kill queue id:%d\n",qid);
  45. return 0;
  46. }
Copyright © Linux教程網 All Rights Reserved