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

L.M*_*lin 3 linux posix file-permissions ipc shared-memory

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

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

有人有任何想法吗?

Mic*_*rny 8

这可能是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>.)
Run Code Online (Sandbox Code Playgroud)

因此,为了允许创建世界可写的文件,您需要设置允许它的umask,例如:

umask(0);
Run Code Online (Sandbox Code Playgroud)

像这样设置,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);
}
Run Code Online (Sandbox Code Playgroud)