|
消息队列是一个存放在内核中的消息链表,每个消息队列由消息队列标识符标识。与管道不同的是,消息队列存放在内核中,只有在内核重启(操作系统重启)或显式地删除一个消息队列时,该消息队列才会被真正的删除。
操作消息队列时,需要用到一些数据结构,下面是几个重要的数据结构。
1、消息缓冲结构
向消息队列发送消息时,必须组成合理的数据结构。Linux 系统定义了一个模板数据结构 msgbuf:#include <linux/msg.h>
/* message buffer for msgsnd and msgrcv calls */
struct msgbuf {
long mtype; /* type of message */
char mtext[1]; /* message text */
};
上面结构体中的 mtype 字段代表消息类型。给消息指定类型,可以使得消息在一个队列中重复使用。mtext 字段指消息内容。
注意:mtext 虽然定义为 char 类型,但并不标识消息只能是一个字符,消息内容可以为任意类型,由用户根据需要定义,如下是自定义的一个消息结构:
struct sefdefbuf {
long mtype;
struct student stu;
};
消息队列中的消息是受大小限制的,由 <linux/msg.h> 中的宏 MSGMAX 给出消息的最大长度。( #define MSGMAX 8192 )
2、msqid_ds 内核数据结构
Linux 内核中,每个消息队列都维护一个结构体 msqid_ds ,此结构体保存着消息队列当前的状态信息。该结构体定义在头文件 linux/msg.h 中,具体定义如下:
/* Obsolete, used only for backwards compatibility and libc5 compiles */
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_last : 指向消息队列中的最后一条消息。 msg_stime : 向消息队列发送最后一条消息的时间。 msg_rtime : 从消息队列取出最后一条消息的时间。 msg_cbytes : 消息队列中所有消息所占的字节数。 msg_lspid : 向消息队列发送最后一条消息的进程 ID 。 msg_lrpid : 从消息队列读取最后一条消息的进程 ID 。 3、ipc_perm 内核数据结构
结构体 ipc_perm 保存着消息队列的一些重要信息,比如消息队列关联的键值,消息队列的用户 ID ,组 ID ,它定义在头文件 linux/ipc.h 中:
/* Obsolete, used only for backwards compatibility and libc5 compiles */
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;
}; 几个主要字段的含义如下:
关于消息队列的创建与读写:http://www.groad.net/bbs/read.php?tid-1124.html
|
|