0

Consider the following C program:

#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <sys/types.h>
#include <string.h>

int main() {
    const char* name = "/memmap_ipc_shm";
    int shmFd = shm_open(name, O_RDWR | O_CREAT, 0777);
    if (shmFd < 0) {
        fprintf(stderr,"bad shmfd opening %s: %s\n", name, strerror(errno));
        return -1;
    }
    return 0;
}

When I run it on my GNU/Linux system (Devuan Beowulf, Linux 5.10.0-9, amd64 CPU), I get:

bad shmfd opening /memmap_ipc_shm: Permission denied

Why am I denied permission? I'm pretty sure I followed all the guidelines in the man shm_open page, my requested permissions seem ok - so what's wrong?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

2 Answers2

1

On Linux, you may check the permission of the following directory:

/dev/shm

If your program cannot create the file: /dev/shm/memmap_ipc_shm, then it will get this "Permission denied" error when calling shm_open().

You may arrange to let your program have proper access on this directory to create the file designated as name in your shm_open() call.

On the other hand, you may try the following to verify that the "Permission denied" error IS due to the insufficient file access privileges:

  1. run your test program as "root"
  2. sudo chmod 0777 /dev/shm
zerox
  • 307
  • 3
  • 11
0

This may be happening when you have already created this shared memory object, but perhaps without the appropriate deletion/destruction. Try calling shm_unlink(name) to ensure that's the case (or even do so as root if you encounter a permission failure again).

Note that this behavior seems to clash with the man page:

O_EXCL If O_CREAT was also specified, and a shared memory object with the given
       name already exists, return an error.  The check for the existence of the
       object, and its creation if it does not exist, are performed atomically.
einpoklum
  • 118,144
  • 57
  • 340
  • 684