【问题标题】:how to provide synchronization between two processes using unnamed semaphores?如何使用未命名的信号量在两个进程之间提供同步?
【发布时间】:2015-03-23 11:41:25
【问题描述】:

谁能解释“如何使用未命名的信号量在两个进程之间提供同步?”。在使用信号量时,需要什么函数调用以及信号量如何共享共享内存区域。同步调用 mmap() 函数有什么用。

【问题讨论】:

    标签: c multithreading semaphore


    【解决方案1】:

    来自sem_init 手册页:

       If pshared is non-zero, then the semaphore is shared between processes,
       and should be located in a region of shared  memory  (see  shm_open(3),
       mmap(2),  and  shmget(2)).   (Since a child created by fork(2) inherits
       its parent's memory mappings, it can also access the  semaphore.)   Any
       process  that  can  access  the shared memory region can operate on the
       semaphore using sem_post(3), sem_wait(3), etc.
    

    因此,您应该使用shm_open+mmapshmget+shmat 创建和附加共享内存。然后使用sem_init 在地址处创建未命名的信号量。使用fork() 系统调用创建的子进程继承父进程的内存映射,因此您也可以在子进程中访问未命名的信号量。

    【讨论】:

      猜你喜欢
      • 2015-05-27
      • 1970-01-01
      • 2023-01-29
      • 1970-01-01
      • 2019-06-05
      • 2021-04-25
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多