struct msqid_ds{
struct ipc_perm msg_perm; /* read_write perms: Section 3.3 */
struct msg *msg_first; /* ptr to first message on queue */
struct msg *msg_last; /* ptr to last message on queue */
msglen_t msg_cbytes; /* current # bytes on queue */
msgqnum_t msg_qnum; /* current # of messages on queue */
msglen_t msg_qbytes; /* max # of bytes allowed on queue */
pid_t msg_lspid; /* pid of last msgsnd() */
pid_t msg_lrpid; /* pid of last msgrcv() */
time_t msg_stime; /* time of last msgsnd() */
time_t msg_rtime; /* time of last msgrcv() */
time_t msg_ctime; /* time of last msgctl() (that changed the above) */
};
#include <sys/msg.h>
int msgget(key_t key, int oflag);
该函数用于创建一个新的消息队列或访问一个已存在的消息队列,返回一个整数标识符。
当创建一个新的消息队列时,msqid_ds结构的如下成员被初始化:
* msg_perm结构的uid和cuid成员被设置成当前进程的有效用户ID,gid和cgid成员被设置成当前进程的有效ID;
* oflag中的读写权限位存放在msg_perm.mode中;
* msg_qnum、msg_lspid、msg_lrpid、msg_stime和msg_rtime被置位0;
* msg_ctime被设置成当前时间;
* msg_qbytes被设置成系统限制值;
int msgsnd(int msqid, const void *ptr, size_t length, int flag);
ptr是一个结构指针,具有如下的模板
struct msgbuf{
long mtype; /* message type, must be > 0 */
char mtext[1]; /* message data */
}
ssize_t msgrcv(int msqid, void *ptr, size_t length, long type, int flag);
type指定希望从给定的队列中读取什么样的消息:
* type等于0,返回队列中的第一个消息(也即最早的消息);
* type大于0,返回其类型值位type的第一个消息;
* type小于0,返回其类型值小于或等于type的绝对值最小的消息类型的第一个消息;
int msgctl(int msqid, int cmd, struct msqid_ds *buff);
msgctl提供3个命令:
IPC_RMID 从系统中删除由msqid指定的消息队列,当前在该队列上的任何消息都被丢弃;
IPC_SET 给指定的消息队列设置其msqid_ds结构下的4个成员:msg_perm.uid、msg_perm.gid、msg_perm.mode和msg_qbytes
IPC_STAT 给调用者返回与所指定消息队列对应的当前msqid_ds结构