【发布时间】:2016-04-29 09:00:50
【问题描述】:
我目前正在使用 POSIX 消息队列做一个最小的 IPC。我有一个管道只能将 uint8_t 作为命令传递,而另一个管道将传递长度不超过 128 个字符的字符串。命令管道工作正常。但是stringpipe总是会给我错误号90,这意味着message too long。我写了一个最小的例子来演示这个问题(请注意:我把它保持在最低限度,所以除了收到错误之外没有任何错误处理)。
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <stdio.h>
int msg_size = 128;
int send()
{
struct mq_attr attr = {0, 10, msg_size + 1, 0};
mqd_t mq = mq_open("/test", O_RDWR | O_CREAT, 00644, &attr);
char msg[msg_size] = {0};
strncpy(msg, "this_is_a_test", msg_size);
mq_send(mq, msg, msg_size, 0);
}
int recv()
{
struct mq_attr attr = {0, 10, msg_size + 1, 0};
mqd_t mq = mq_open("/test", O_RDWR | O_CREAT, 00644, &attr);
char msg[msg_size] = {0};
int res = mq_receive(mq, msg, msg_size, NULL);
if (res == -1)
{
printf("Errno: %d\n", errno);
}
else
{
printf("Message: %s\n", msg);
}
}
int main()
{
send();
recv();
return 0;
}
编译:
g++ -o mq mq.c -lrt
【问题讨论】:
-
为什么在没有 C++ 代码的情况下使用 C++ 编译器进行编译?建议使用
gcc。编译时,始终启用所有警告。gcc/g++至少使用:-Wall -Wextra -pedantic我也使用:-Wconversion -std=gnu99。对于贴出的代码,编译器会输出很多警告信息。修复这些警告。 -
1) 一个消息队列只需要打开一次,与使用该队列的进程数量无关。 2)
struct mq_attr中的实际字段列表取决于实现,因此不能使用初始化程序,而是按字段名称设置每个字段,类似于:mset( &attr, '\0', sizeof( attr ) ); attr.mq_maxmsg = 300; attr.mq_msgsize = MSG_SIZE; attr.mq_flags = 0;