[英]Bad address with mq_open
我正在尝试使用mq_open打开一个简单的队列,但我不断收到错误消息:
"Error while opening ...
Bad address: Bad address"
而且我不知道为什么。
int main(int argc, char **argv) {
struct mq_attr attr;
//max size of a message
attr.mq_msgsize = MSG_SIZE;
attr.mq_flags = 0;
//maximum of messages on queue
attr.mq_maxmsg = 1024 ;
dRegister = mq_open("/serverQRegister",O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR,0664, &attr);
if(dRegister == -1)
{
perror("mq_open() failed");
exit(1);
}
}
我按照建议更新了代码,但仍然出现错误(“无效参数”):
#include <stdio.h>
#include <stdlib.h>
#include <mqueue.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include "serverDefinitions.h"
mqd_t dRegister;
int main(int argc, char **argv) {
struct mq_attr attr;
//setting all attributes to 0
memset(&attr, 0, sizeof attr);
//max size of a message
attr.mq_msgsize = MSG_SIZE; //MSG_SIZE = 4096
attr.mq_flags = 0;
//maximum of messages on queue
attr.mq_maxmsg = 1024;
dRegister = mq_open("/serverQRegister", O_RDONLY | O_CREAT, 0664, &attr);
if (dRegister == -1) {
perror("mq_open() failed");
exit(1);
}
return 0;
}
这个电话
... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR,0664, &attr);
指定太多参数。 该mode
似乎已指定两次。
它应该是
... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR, &attr);
要么
... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, 0664, &attr);
关于EINVAL,该man mq_open
指出:
EINVAL
O_CREAT在oflag中指定,并且attr不为NULL,但是attr-> mq_maxmsg或attr-> mq_msqsize无效。 这两个字段都必须大于零。 在没有特权的进程中(不具有CAP_SYS_RESOURCE功能), attr-> mq_maxmsg必须小于或等于msg_max限制,而attr-> mq_msgsize必须小于或等于msgsize_max限制。 另外,即使在特权进程中, attr-> mq_maxmsg也不能超过HARD_MAX限制。 (有关这些限制的详细信息,请参见mq_overview(7)。)
attr
的初始化达到mq_maxmsg
或/和mq_msgsize
之一或两者的mq_msgsize
。 阅读man 7 mq_overview
有关如何找出限制的信息。
mq_open()是一个可变函数,可以接受2或4个参数,但给它5个,这是错误的。
使它只是
dRegister = mq_open("/serverQRegister",O_RDONLY | O_CREAT, 0664, &attr);
或使用符号名S_IRUSR | S_IWUSR而不是八进制表示。
您还应该初始化attr
所有成员,如果提供了mq_attr,则必须同时设置mq_msgsize和mq_maxmsg,这样就可以了
struct mq_attr attr;
memset(&attr, 0, sizeof attr);
//max size of a message
attr.mq_msgsize = MSG_SIZE;
attr.mq_maxmsg = 10;
(请注意,mq_maxmsg必须小于将sysctl fs.mqueue.msg_max
命令设置为的值)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.