Understanding the posix interprocess semaphore

后端 未结 2 1092
醉梦人生
醉梦人生 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: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

提交回复
热议问题