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?>
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