POSIX共享内存和semaphores的权限被open调用错误地设置了

7 人关注

我试图创建一个共享内存,它将被几个进程使用,这些进程不一定由同一个用户启动,所以我用下面一行创建了这个段。

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

然而,当我检查在/dev/shm创建的文件的权限时,它们是。

-rw----r-- 1 lmccauslin lmccauslin 1784 2012-08-10 17:11 /dev/shm/CubeConfigShare not -rw----rw- as I'd expected.

/dev/shm的权限是lrwxrwxrwx。

同样的事情也发生在以类似方式创建的信号灯上。

kernel version: 3.0.0-23-generic

glibc version: EGLIBC 2.13-20ubuntu5.1

有没有人有什么想法?

linux
posix
ipc
file-permissions
shared-memory
L.McCauslin
L.McCauslin
发布于 2012-08-11
2 个回答
Michał Górny
Michał Górny
发布于 2018-01-12
已采纳
0 人赞同

这可能是 umask .

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(0);

像这样设置,umask就不会再影响所创建文件的任何权限。然而,你应该注意到,如果你在没有明确指定权限的情况下创建另一个文件,它也将是世界可写的。

因此,你可能只想暂时清除umask,然后再恢复它。

#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);
    
khushbu
khushbu
发布于 2018-01-12
0 人赞同

据我所知,POSIX信号灯是在共享内存中创建的。所以你需要确保用户有

rw permissions to /dev/shm for the semaphores to be created.

然后,作为一个方便的选择,在你的/etc/fstab文件中加入以下一行来装载tmpfs。

none /dev/shm tmpfs defaults 0 0

这样,当你的机器被 rebooted ,权限从一开始就被设置好了。

三台机器中有两台的/dev/shm设置为drwxrwxrwx,不允许创建semaphores的机器设置为drwxr_xr_x。
你也可以看一下共享内存的限制。