Sam Hooke

shm_open not working under systemd

I had a binary which worked when run manually, but failed when run as a systemd service with:

Assertion `fd != -1' failed.

The failing assertion happened here:

char name[] = "my-memory-123";
int fd = shm_open(name, O_CREAT | O_RDWR, 0600);
assert(fd != -1);  // <- HERE

Looking at the man page for shm_open, I found that this function typically creates shared memory on the filesystem under /dev/shm.

Looking at /dev/shm quickly illuminated the problem. To test, I had manually run the command as the user vagrant, which had created the shared memory owned by vagrant:

$ ls -lrth /dev/shm/
total 128K
-rw------- 1 vagrant vagrant 128K Feb  5 14:36 my-memory-123

This was preventing me from subsequently running the command as a systemd service, which runs as the user somethingd.

To fix this, I deleted the shared memory:

$ sudo rm -rf /dev/shm/my-memory-123

Then I was able to run the systemd service without getting an assertion.

Checking the shared memory again now shows it is owned by somethingd:

$ ls -lrth /dev/shm/
total 128K
-rw------- 1 somethingd somethingd 128K Feb  5 14:41 my-memory-123