mq_receive: 消息太长 [英] mq_receive: message too long

查看:34
本文介绍了mq_receive: 消息太长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用队列实现 2 个进程之间的通信.问题是当我调用函数 mq_receive 时,我得到这个错误:消息太长.

I am implementing a communication between 2 processes using a queue. The problem is that when I call the function mq_receive, I get this error: Message too long.

我做了以下事情:

struct mq_attr attr;

long size = attr.mq_msgsize;
.... // initializing the queue "/gateway"

int rc = mq_receive(gateway, buffer, size, &prio);

如果我打印大小值,我得到 size=1,而当我打印相同大小但来自另一个程序(通过相同机制获得)时,我得到的不是长整数(-1217186280)...

If I print the size value, I get size=1, while when I print the same size but from another program (got by the same mechanism), I get something not long integer ( -1217186280 )...

我该如何解决这个错误?....所以当 size = 1 时,我相信说消息太长"是正确的,但为什么是 1?

How can I solve this error?....so while size = 1, I believe it's right to say "message too long" but why is 1?

附:我也试过把:

int rc = mq_receive(gateway, buffer, sizeof(buffer), &prio);

但没有结果.

推荐答案

看来您需要更仔细地阅读文档.当您调用 mq_receive 时,您应该传递目标缓冲区的大小.此大小必须大于队列的 mq_msgsize 属性.此外,您似乎在队列属性初始化中存在错误,导致无法正确调用 mq_receive.这是标准消息队列会话:

It seems like you need to read the docs more carefully. When you call mq_receive you should pass size of the destination buffer. This size must be greater than the mq_msgsize attribute of the queue. In addition, it seems like you have an error in queue attributes initialisation that makes proper mq_receive call impossible. Here is standard message queue session:

  1. 填写mq_attr结构(doc):

struct mq_attr attr;  
attr.mq_flags = 0;  
attr.mq_maxmsg = 10;  
attr.mq_msgsize = 33;  
attr.mq_curmsgs = 0;  

  • 在主进程中使用 mq_open 创建队列(doc):

    mqd_t queue = mq_open(qname, O_CREAT|O_RDWR, 0644, &attr);
    

  • 在写入进程中打开写入队列:

  • In writer process open queue for writing:

    mqd_t queue = mq_open(qname, O_WRONLY);
    

    并发送一些文本.文本长度必须小于队列的 mq_msgsize 属性 (doc):

    And send some text. Length of the text must be lesser than mq_msgsize attribute of the queue (doc):

    mq_send(queue, "some message", strlen("some message")+1, 1);
    

  • 在阅读器进程中打开阅读队列:

  • In reader process open queue for reading:

    mqd_t queue = mq_open(qname, O_RDONLY);
    

    然后分配缓冲区并接收消息.缓冲区大小 *必须大于队列的 mq_msgsize 属性.这里我们创建 50 字节的缓冲区,而 mq_msgsize == 33 (doc):

    And then allocate buffer and receive message. Size of buffer *must be greater than the mq_msgsize attribute of the queue. Here we create 50-byte buffer while mq_msgsize == 33 (doc):

    char rcvmsg[50];
    int iret = mq_receive(queue, rcvmsg, 50, NULL);
    

  • 还请记住,您应该使用 %ld 打印 long 而不是 %d.

    Also remember that you should use %ld for print long instead of %d.

    这篇关于mq_receive: 消息太长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆