POSIX 共享内存和信号量权限由打开调用错误设置



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

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 通用

glibc 版本: EGLIBC 2.13-20ubuntu5.1

有人有什么想法吗?

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

这样设置,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);
}

据我了解,POSIX 信号量是在共享内存中创建的。因此,您需要确保用户具有

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

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

none/dev/shm tmpfs defaults 0 0

这样,当您的计算机重新启动时,从一开始就设置权限。

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

------共享内存限制--------

max number of segments = 4096 max seg size (kbytes) = 18014398509465599
max total shared memory (kbytes) = 18446744073642442748 min seg size (bytes) = 1

最新更新