How to share semaphores between processes using shared memory

Sicioldr picture Sicioldr · Dec 2, 2011 · Viewed 68k times · Source

I have to synchronize N client processes with one server. These processes are forked by a main function in which I declared 3 semaphores. I decided to use POSIX semaphores but I don't know how to share them between these processes. I thought that shared memory should work correctly, but I have some questions:

  • How can I allocate the right space of memory in my segment?
  • Can I use sizeof(sem_t) in size_t field of shmget in order to allocate exactly the space I need?
  • Does anyone have some examples similar to this situation?

Answer

cnicutar picture cnicutar · Dec 2, 2011

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.