Understanding the posix interprocess semaphore

后端 未结 2 1091
醉梦人生
醉梦人生 2021-01-20 06:28

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?

相关标签:
2条回答
  • 2021-01-20 07:01

    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/

    0 讨论(0)
  • 2021-01-20 07:03

    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:

    • Use sem_open("my_sem", ...)
    • Use shm_open and mmap to create a shared region
    0 讨论(0)
提交回复
热议问题