mq_open() - EACCES, Permission denied

2020-07-15 03:04发布

问题:

I'm trying to create a POSIX message queue from a privileged process (waiting for later read), then open this message queue from an unprivileged process (to send message), and the later mq_open() returned: EACCES.

If the create process and open process are both privileged or both unprivileged, mq_open will success.

I checked the mq_open manual, it says EACCES means the caller does not have permission to open it in the specified mode, but I'm not sure what is 'specified mode'...

Create success in privileged process:

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

mq_open("/myMq", (O_RDONLY| O_CREAT), (S_IRWXU | S_IRWXG | S_IRWXO) /* 777 */, &attr);

Open failed in unprivileged process:

mqd_t mqd;
mqd = mq_open("/myMq", (O_WRONLY|O_NONBLOCK));
if ((mqd_t)-1 == mqd) {
    printf("mq_open %d %s\n", errno, strerror(errno)); }

It gives the error: mq_open 13 Permission denied

I'm using CentOS 6.5 64-bit

uname -r
2.6.32-431.el6.x86_64

Can you help me to figure out what the problem is. Thanks in advance.

回答1:

In this case, you're being stung by the umask of the creating process.

The permissions settings are masked against the process umask.

You can use:

mode_t omask;
omask = umask(0);
mq_open("/myMq", (O_RDONLY| O_CREAT), (S_IRWXU | S_IRWXG | S_IRWXO) /* 777 */, &attr);
umask(omask);

but beware of umask-dependent race conditions if you're running in a multi-threaded process.