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)
insize_t
field ofshmget
in order to allocate exactly the space I need? - Does anyone have some examples similar to this situation?
I wrote a sample application where a parent (producer) spawns N child (consumer) threads and uses a global array to communicate data between them. The global array is a circular memory and is protected when data is written on to the array.
Header File:
Source code:
I really doubt if the shared memory approach would ever work.
AFAIK the semaphore is actually just a handle, valid for the process it is opened in. The real semaphore info lies in the kernel memory.
So using the same handle value in other process is not going to work.
Yes, we can use the named semaphore between the two processes. We can open a file.
And other process can use this.
It's easy to share named
POSIX
semaphoresChoose a name for your semaphore
Use
sem_open
withO_CREAT
in the process that creates themOpen semaphores in the other processes
If you insist on using shared memory, it's certainly possible.
I haven't tested the above so it could be completely bonkers.