消息隊列是一個存放在內核中的消息鏈表,每個消息隊列由消息隊列標識符標識。與管道不同的是消息隊列存放在內核中,
只有在內核重啟(即操作系統重啟)或者顯式地刪除一個消息隊列時,該消息隊列才會被真正刪除。
幾個重要的數據結構:
在文件/usr/include/linux/msg.h中
1、消息緩沖結構:
在向消息隊列發送消息時,必須組合成合理的數據結構。linux定義了一個模板數據結構:
struct msgbuf {
long mtype; /* type of message 消息類型,必須 > 0 */
char mtext[1]; /* message text 消息正文,可以是其他任何類型*/
};
結構中的mytype字段代表消息類型。給消息指定類型,可以使得消息在一個隊列中重復使用。mtext字段指消息內容。
注意:
mtext雖然定義為char類型,並不代表消息只能是一個字符,消息內容可以為任意類型,由用戶根據需要定義。如下面
就是用戶定義的一個消息結構:
struct MyMsgBuf {
long mtype; /* type of message */
struct student stu;
};
消息隊列中的消息的大小是受限制的,由宏MSGMAX給出消息的最大長度。
2、msqid_ds內核數據結構
linux內核中,每個消息隊列都維護一個結構體msqid_ds ,此結構體保存着消息隊列當前的狀態信息。
struct msqid_ds {
struct ipc_perm msg_perm;
struct msg *msg_first; /* first message on queue,unused */
struct msg *msg_last; /* last message in queue,unused */
__kernel_time_t msg_stime; /* last msgsnd time */
__kernel_time_t msg_rtime; /* last msgrcv time */
__kernel_time_t msg_ctime; /* last change time */
unsigned long msg_lcbytes; /* Reuse junk fields for 32 bit */
unsigned long msg_lqbytes; /* ditto */
unsigned short msg_cbytes; /* current number of bytes on queue */
unsigned short msg_qnum; /* number of messages in queue */
unsigned short msg_qbytes; /* max number of bytes on queue */
__kernel_ipc_pid_t msg_lspid; /* pid of last msgsnd */
__kernel_ipc_pid_t msg_lrpid; /* last receive pid */
};
各個字段的含義:
msg_perm:是一個ipc_perm(定義在頭文件linux/ipc.h)的結構,保存了消息隊列的存取權限,以及隊列的用戶ID、組ID等信息。
msg_first:指向隊列中的第一條消息
msg_last:指向隊列中的最后一條消息
msg_stime:向消息隊列發送最后一條信息的時間
msg_rtime:從消息隊列取最后一條消息的時間
msg_ctime:最后一次變更消息隊列的時間
msg_lcbytes:消息隊列中所有消息占的字節數
msg_qnum:消息隊列中的消息數目
msg_qbytes:消息隊列的最大字節數
msg_lspid:向消息隊列發送最后一條消息的進程ID
msg_lrpid:從消息隊列讀取最后一條消息的進程ID
3、ipc_perm內核數據結構
結構體ipc_perm保存着消息隊列的一些重要的信息,比如消息隊列關聯的鍵值,消息隊列的用戶ID,組ID等。
定義在linux/ipc.h中。
struct ipc_perm
{
__kernel_key_t key;
__kernel_uid_t uid;
__kernel_gid_t gid;
__kernel_uid_t cuid;
__kernel_gid_t cgid;
__kernel_mode_t mode;
unsigned short seq;
};
幾個主要字段的含義如下:
key:創建消息隊列用到的鍵值key
uid:消息隊列的用戶ID
gid:消息隊列的組ID
cuid:創建消息隊列的進程用戶ID
cgid:創建消息隊列進程組ID