According to my understanding, a semaphore should be usable across related processes without it being placed in shared memory. If so, why does the following code deadlock?
An excellent article on this topic, for future passers-by:
http://blog.superpat.com/2010/07/14/semaphores-on-linux-sem_init-vs-sem_open/
The wording in the manual page is kind of ambiguous.
If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory.
Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.
Yes, but it still has to be in a shared region. Otherwise the memory simply gets copied with the usual CoW and that's that.
You can solve this in at least two ways:
sem_open("my_sem", ...)
shm_open
and mmap
to create a shared region