c - 带有结构的消息太长错误 mq_send
问题描述
我正在尝试设置消息队列 IPC 示例。
问题:我正在尝试制作一个有效的测试用例,其中我使用 mqueue 发送具有各种字段的结构(我正在参考这篇文章)。但是,我遇到了Message too long错误。大多数示例发送 char* 消息,但我想发送具有多个字段的结构。在这个玩具示例中,它只有一个文件路径,但我也想将其他字段添加到结构中,并将结构发送到消息队列中。
工作示例:
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h> // mq_open(), mq_send(), mq_receive()
//#include <errno.h>
//#include <time.h>
#include <string.h> // strncpy(), strlen()
#include <stdio.h> // printf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MSG_SIZE (300)
static mqd_t mqdes = -1;
static struct mq_attr attr;
typedef struct{
char filepath[MSG_SIZE];
} obj;
void sendQueue()
{
obj obj1;
strncpy(obj1.filepath, "this_is_a_test", MSG_SIZE);
if( -1 == mq_send(mqdes, (const char *) &obj1, sizeof(obj1), 0) )
{
perror( "mq_send failed" );
exit( EXIT_FAILURE );
}
else
{
printf("msg sent successfully");
}
}
void recvQueue()
{
obj recv_obj;
ssize_t res = mq_receive(mqdes, (char*) &recv_obj, sizeof(recv_obj), NULL);
if (res == -1)
{
perror("mq_receive failed");
}
else
{
printf("Message: %s\n", recv_obj.filepath);
}
}
int main( void )
{
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
memset( &attr, 0x00, sizeof(struct mq_attr) );
attr.mq_flags = 0;
attr.mq_maxmsg = 10;
attr.mq_msgsize = 1024;
attr.mq_curmsgs = 0;
char *queueName = "/test";
mqdes = mq_open( queueName, O_RDWR|O_CREAT, mode, &attr);
if( -1 == mqdes )
{
perror( "mq_open failed");
exit( EXIT_FAILURE );
}
// implied else, mq_open successful
sendQueue();
recvQueue();
return 0;
}
编译
gcc -std=gnu99 test.c -lrt -o test
在 Linux 18.04.3 LTS 上。
解决方案
mq_receive 中的第三个参数应该是 1024,而不是发送消息的大小。根据 mq_receive 的手册页“msg_len 参数指定 msg_ptr 指向的缓冲区的大小;这必须大于或等于队列的 mq_msgsize 属性(请参阅 mq_getattr(3))。”
推荐阅读
- sql - 如何为 ID IN SQL 获取超过 1 个事务的 Null 值?使用两个事实表
- javascript - 如何在 iframe 中编辑内容或添加样式?
- r - 有没有办法使用重复循环的最后一个值来制作数据框?
- mysql - MySQL内存没有被释放
- vscode-debugger - 本地调试 CluedIn 集成的最佳方法
- css - 如何在 CSS 中删除播放按钮和徽标 img 下的边框?
- javascript - 在元素外部单击时切换元素并移除其可见性 - JavaScript
- reactjs - 如何访问 ReduxSlice 中的状态
- kubernetes - 如何从 HTTP 请求绑定掌舵图中的值?
- r - 有没有办法从 R 中的现有列名生成年份列?