消息队列msg_queue API

114 阅读1分钟

[TOC]

  • 数据结构

    struct msg_queue {
    	struct kern_ipc_perm q_perm;
    	time64_t q_stime;		/* last msgsnd time */
    	time64_t q_rtime;		/* last msgrcv time */
    	time64_t q_ctime;		/* last change time */
    	unsigned long q_cbytes;		/* current number of bytes on queue */
    	unsigned long q_qnum;		/* number of messages in queue */
    	unsigned long q_qbytes;		/* max number of bytes on queue */
    	struct pid *q_lspid;		/* pid of last msgsnd */
    	struct pid *q_lrpid;		/* last receive pid */
    
    	struct list_head q_messages;
    	struct list_head q_receivers;
    	struct list_head q_senders;
    } __randomize_layout;
    

    常用的消息队列的封装格式如下。

    struct msgbuf {
        long mtype;       /* message type, must be > 0 */
        char mtext[1];    /* message data */
    };
    
  • 创建

    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    
    int msgget(key_t key, int msgflg);
    
  • 收发

    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    
    int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
    
    ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
                   int msgflg);
    
  • 控制

    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/msg.h>
    
    int msgctl(int msqid, int cmd, struct msqid_ds *buf);