進程間通信方式——消息隊列 轉載出處:https://blog.csdn.net/skyroben/article/details/72520501

轉載出處:https://blog.csdn.net/skyroben/article/details/72520501

消息隊列是消息的鏈接表,存放在內核中並由消息隊列標識符標識。 標識符是IPC對象的內部名, 而它的外部名則是key(鍵), 它的基本類型是key_t, 在頭文件<sys/types.h>中定義爲長整型.。鍵由內核變換成標識符。
  用戶可以從消息隊列中讀取數據和添加消息,其中發送進程添加消息到隊列的末尾,接收進程在隊列的頭部接收消息,消息一旦被接收,就會從隊列中刪除。和FIFO有點類似,但是它可以實現消息的隨機查詢,比FIFO具有更大的優勢(比如按消息的類型字段取消息)。

2.消息隊列的三個數據結構

linux內核採用的結構msqid_ds管理消息隊列

  1. struct msqid_ds
  2. {
  3. struct ipc_perm msg_perm; //消息隊列訪問權限
  4. struct msg *msg_first; //指向第一個消息的指針
  5. struct msg *msg_last; //指向最後一個消息的指針
  6. ulong msg_cbytes; //消息隊列當前的字節數
  7. ulong msg_qnum; //消息隊列當前的消息個數
  8. ulong msg_qbytes; //消息隊列可容納的最大字節數
  9. pid_t msg_lsqid; //最後發送消息的進程號ID
  10. pid_t msg_lrqid; //最後接收消息的進程號ID
  11. time_t msg_stime; //最後發送消息的時間
  12. time_t msg_rtime; //最後接收消息的時間
  13. time_t msg_ctime; //最近修改消息隊列的時間
  14. };

linux內核採用的結構msg_queue來描述消息隊列

  1. struct msg_queue {
  2. structkern_ipc_perm q_perm;
  3. time_tq_stime; /* last msgsndtime */
  4. time_tq_rtime; /* last msgrcvtime */
  5. time_tq_ctime; /* last changetime */
  6. unsignedlong q_cbytes; /* current number of bytes on queue*/
  7. unsignedlong q_qnum; /* number of messages inqueue */
  8. unsignedlong q_qbytes; /* max number of bytes on queue */
  9. pid_tq_lspid; /* pid oflast msgsnd */
  10. pid_tq_lrpid; /* lastreceive pid */
  11. structlist_head q_messages;
  12. structlist_head q_receivers;
  13. structlist_head q_senders;
  14. };

syetem V IPC 爲每一個IPC結構設置了一個ipc_perm結構,該結構規定了許可權和所有者

  1. struct ipc_perm
  2. {
  3. key_t key; //調用shmget()時給出的關鍵字
  4. uid_t uid; //共享內存所有者的有效用戶ID
  5. gid_t gid; //共享內存所有者所屬組的有效組ID
  6. uid_t cuid; //共享內存創建 者的有效用戶ID
  7. gid_t cgid; //共享內存創建者所屬組的有效組ID
  8. unsigned short mode; //Permissions + SHM_DEST和SHM_LOCKED標誌
  9. unsignedshort seq; //序列號
  10. };

3.與消息隊列有關的函數

3.1創建打開消息隊列






























3.2添加消息



3.3讀取消息



3.4獲得或修改消息隊列或者刪除消息隊列



4.消息隊列讀取數據工作模式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章