问题
I am trying to open a simple queue using mq_open but I keep getting error:
"Error while opening ...
Bad address: Bad address"
And I have no idea why.
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);
}
}
I updated code as suggested but still getting error ("invalid argument"):
#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;
}
回答1:
This call
... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR,0664, &attr);
specifies too many parameters. The mode seems to have been specified twice.
It should be
... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR, &attr);
or
... = mq_open("/serverQRegister",O_RDONLY | O_CREAT, 0664, &attr);
Regarding EINVAL, the man mq_open states:
EINVAL
O_CREAT was specified in oflag, and attr was not NULL, but attr->mq_maxmsg or attr->mq_msqsize was invalid. Both of these fields must be greater than zero. In a process that is unprivileged (does not have the CAP_SYS_RESOURCE capability), attr->mq_maxmsg must be less than or equal to the msg_max limit, and attr->mq_msgsize must be less than or equal to the msgsize_max limit. In addition, even in a privileged process, attr->mq_maxmsg cannot exceed the HARD_MAX limit. (See mq_overview(7) for details of these limits.)
The initialisation of attr hits the limits for either one or both of mq_maxmsg or/and mq_msgsize. Read man 7 mq_overview on how to find out the limits.
回答2:
mq_open() is a varadic function and it can take either 2 or 4 arguments, but you give it 5, which is wrong.
Make it just
dRegister = mq_open("/serverQRegister",O_RDONLY | O_CREAT, 0664, &attr);
Or use the symbolic names, S_IRUSR | S_IWUSR instead of the octal representation.
You should also initialize all the members of attr, and if you supply the mq_attr, you must set both mq_msgsize and mq_maxmsg, so make it
struct mq_attr attr;
memset(&attr, 0, sizeof attr);
//max size of a message
attr.mq_msgsize = MSG_SIZE;
attr.mq_maxmsg = 10;
(note, mq_maxmsg must be less than what the command sysctl fs.mqueue.msg_max is set to)
来源:https://stackoverflow.com/questions/30011979/bad-address-with-mq-open