open调用设置的POSIX共享内存和信号量权限不正确

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 并不像我预期的那样是-rw----rw-
/dev/shm的权限为lrwxrwxrwx。
类似地,使用相似的方式创建信号量也会出现完全相同的情况。
内核版本:3.0.0-23-generic
glibc版本:EGLIBC 2.13-20ubuntu5.1
有人有什么想法吗?
2个回答

10

可能是 umask

引用 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,例如:

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);
}

0

据我所知,POSIX信号量是在共享内存中创建的。因此,您需要确保用户对/dev/shm具有rw权限才能创建信号量。

然后,作为一个方便的选项,将以下行放入您的/etc/fstab文件中以挂载tmpfs:

none /dev/shm tmpfs defaults 0 0

这样,当您的机器重新启动时,权限就会从一开始就设置正确。

其中两个/dev/shm设置为drwxrwxrwx,而不允许创建信号量的机器则设置为drwxr_xr_x。
您还可以查看共享内存限制:

------ 共享内存限制 --------
最大段数=4096
最大段大小(kbytes)=18014398509465599 最大总共享内存(kbytes)=18446744073642442748
最小段大小(字节)=1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接