Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share semaphores between processes using shared memory

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?
like image 661
Sicioldr Avatar asked Dec 02 '11 16:12

Sicioldr


People also ask

Can semaphore be shared between processes?

If you specify a non-zero value for the pshared argument, the semaphore can be shared between processes. If you specify the value zero, the semaphore can be shared among threads of the same process. The sem_open function establishes a connection between a named semaphore and the calling process.

How do you declare semaphores in shared memory?

To declare a sem_t inside a shared memory segment, do this: /* shmPtr is a pointer to the base of your shared memory area */ sem_t *sem = (sem_t*)shmPtr; void *usableSharedMemory = (char*)shmPtr + sizeof(sem_t); .

Are semaphores shared memory?

Example: Using semaphore set and shared memory functionsThe buffer is a shared memory segment. The process synchronization is done using semaphores. Use the Create C Module (CRTCMOD) and the Create Program (CRTPGM) commands to create this program. Call this program with no parameters before calling the client program.

What is the use of semaphores in shared memory?

A semaphore lock on the shared memory buffer reference allows processes accessing the shared memory to prevent a daemon from writing to the memory segment currently being accessed.


1 Answers

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.

like image 178
cnicutar Avatar answered Oct 02 '22 03:10

cnicutar