How to share semaphores between processes using shared memory

It’s easy to share named POSIX semaphores

  • Choose a name for your semaphore

    #define SNAME "/mysem"
    
  • Use sem_open with O_CREAT in the process that creates them

    sem_t *sem = sem_open(SNAME, O_CREAT, 0644, 3); /* Initial value is 3. */
    
  • Open semaphores in the other processes

    sem_t *sem = sem_open(SEM_NAME, 0); /* Open a preexisting semaphore. */
    

If you insist on using shared memory, it’s certainly possible.

int fd = shm_open("shmname", O_CREAT, O_RDWR);
ftruncate(fd, sizeof(sem_t));
sem_t *sem = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE,
    MAP_SHARED, fd, 0);

sem_init(sem, 1, 1);

I haven’t tested the above so it could be completely bonkers.

Leave a Comment