1

当我在执行 mq_send()/mq_receive() 之前和之后使用“cat /dev/mqueue/myqueue”检查消息队列的 QSIZE 时,mq_recieve() 之后似乎有一些剩余字节留在队列中。我的小测试程序如下:

#include <stdio.h>
#include <stdlib.h>

#include <mqueue.h>


#define MSG_LEN 8192 // As per mq_msgsize as returned by mq_getattr() on CentOS 7 x86_64 


int main(void)
{
    mqd_t mq;


    /* Create a message queue */
    if ((mq = mq_open("/myqueue", O_RDWR|O_NONBLOCK|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR, NULL)) == -1) {
        perror("Error calling mq_open()");
        exit(EXIT_FAILURE);
    }


    /* Create a message */

    char msg[MSG_LEN] = {" "};

    int msglen = snprintf(msg, MSG_LEN, "Hello, World!"); // msglen is 13 without the terminating '\0' 

    if (msglen < 0) {
        fprintf(stderr, "Error calling snprintf()\n");
        exit(EXIT_FAILURE);
    }


    /*
     * QSIZE here using "cat /dev/mqueue/myqueue" is: 0
     * OK
     */


    /* Send the message */

    if (mq_send(mq, msg, msglen + 1, 1) == -1) { // add 1 to msglen for the termining '\0'
        perror("Error calling mq_send()");
        exit(EXIT_FAILURE);
    }


    /*
     * QSIZE here using "cat /dev/mqueue/myqueue" is: 62
     * Why not 14?
     */


    /* Receive the message */

    if (mq_receive(mq, msg, MSG_LEN, NULL) == -1) {
        perror("Error calling mq_receive()");
        exit(EXIT_FAILURE);
    }


    /*
     * QSIZE here using "cat /dev/mqueue/myqueue" is: 48
     * Why not 0?
     */


    exit(EXIT_SUCCESS);
}

我不明白为什么最初将 62 字节放入队列中,而在发送和接收 14 字节消息后留下了 48 字节的剩余部分。任何帮助将非常感激。

亲切的问候

约翰·达菲

4

1 回答 1

1

我相信消息队列在文件中存储了一些簿记信息。从mq_overview()手册页:

目录中每个文件的内容都包含一行,其中包含有关队列的信息:

       $ cat /dev/mqueue/mymq
       QSIZE:129     NOTIFY:2    SIGNO:0    NOTIFY_PID:8260

http://man7.org/linux/man-pages/man7/mq_overview.7.html

于 2015-02-11T21:23:18.277 回答