【发布时间】:2015-03-23 11:41:25
【问题描述】:
谁能解释“如何使用未命名的信号量在两个进程之间提供同步?”。在使用信号量时,需要什么函数调用以及信号量如何共享共享内存区域。同步调用 mmap() 函数有什么用。
【问题讨论】:
标签: c multithreading semaphore
谁能解释“如何使用未命名的信号量在两个进程之间提供同步?”。在使用信号量时,需要什么函数调用以及信号量如何共享共享内存区域。同步调用 mmap() 函数有什么用。
【问题讨论】:
标签: c multithreading semaphore
来自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+mmap 或shmget+shmat 创建和附加共享内存。然后使用sem_init 在地址处创建未命名的信号量。使用fork() 系统调用创建的子进程继承父进程的内存映射,因此您也可以在子进程中访问未命名的信号量。
【讨论】: