POSIX shared memory and semaphores permissions set incorrectly by open calls

前端 未结 2 1486
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 05:10

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 follo

相关标签:
2条回答
  • 2020-12-11 05:39

    From what I understand, POSIX semaphores are created in shared memory. So you need to make sure that users have

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

    Then, as a handy option, put the following line in your /etc/fstab file to mount tmpfs:

    none /dev/shm tmpfs defaults 0 0

    So that when your machine is rebooted, the permissions are set right from the start.

    Two of the three had /dev/shm set to drwxrwxrwx and the machine that would not allow creation of semaphores had it set to drwxr_xr_x.
    You can also look at shared memory limits:

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

    0 讨论(0)
  • 2020-12-11 05:40

    It's probably 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>.)
    

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

    umask(0);
    

    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.

    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);
    }
    
    0 讨论(0)
提交回复
热议问题