c-如何使用未命名信号量在两个进程之间提供同步



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

来自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()系统调用创建的子进程继承父进程的内存映射,因此您也可以在子进程中访问未命名的信号量。

最新更新