POSIX共享内存和信号灯权限因打开调用而设置不正确 [英] POSIX shared memory and semaphores permissions set incorrectly by open calls

查看:96
本文介绍了POSIX共享内存和信号灯权限因打开调用而设置不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个共享内存,该内存将由多个进程使用,而不必由同一用户启动,因此我用以下行创建了该段:

I'm trying to create a shared memory which will be used by several processes, which will not necessarily be started by the same user, so I create the segment with the following line:

fd = shm_open(SHARE_MEM_NAME,O_RDWR | O_CREAT,0606);

但是,当我检查在/dev/shm中创建的文件的权限时,它们是:

however, when I check out the permissions of the file created in /dev/shm they are:

-rw----r-- 1 lmccauslin lmccauslin 1784 2012-08-10 17:11 /dev/shm/CubeConfigShare 不是我所期望的-rw----rw-.

/dev/shm的权限为lrwxrwxrwx.

the permissions for /dev/shm are lrwxrwxrwx.

相同创建的信号量也会发生完全相同的事情.

The exact same thing happens with the semaphore created similarly.

内核版本:通用3.0.0-23

kernel version: 3.0.0-23-generic

glibc版本:EGLIBC 2.13-20ubuntu5.1

glibc version: EGLIBC 2.13-20ubuntu5.1

有人有什么主意吗?

推荐答案

可能是 umask .

引用shm_open手册页:

Citing the manpage of shm_open:

   O_CREAT    Create  the  shared memory object if it does not exist.  The user and
              group ownership of the object are taken from the corresponding effec‐
              tive IDs of the calling process, and the object's permission bits are
              set according to the low-order 9 bits of mode, except that those bits
              set in the process file mode creation mask (see umask(2)) are cleared
              for the new object.  A set of macro constants which can  be  used  to
              define  mode  is  listed  in open(2).  (Symbolic definitions of these
              constants can be obtained by including <sys/stat.h>.)

因此,为了允许创建可全局写入的文件,您需要设置一个允许它的umask,例如:

So, in order to allow creating files which are world-writable, you'd need to set an umask permitting it, for example:

umask(0);

这样设置,umask将不再影响对创建的文件的任何权限.但是,请注意,如果您随后创建另一个文件而未明确指定权限,那么该文件也将是世界可写的.

Set like this, umask won't affect any permissions on created files anymore. However, you should note that if you will then create another file without specifying permissions explicitly, it will be world-writable as well.

因此,您可能只想暂时清除umask,然后将其还原:

Thus, you may want to clear the umask only temporarily, and then restore it:

#include <sys/types.h>
#include <sys/stat.h>

...

void yourfunc()
{
    // store old
    mode_t old_umask = umask(0);

    int fd = shm_open(SHARE_MEM_NAME,O_RDWR | O_CREAT,0606);

    // restore old
    umask(old_umask);
}

这篇关于POSIX共享内存和信号灯权限因打开调用而设置不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆