[英]posix semaphore trouble
I supposed that my program should work like this: 1) initializing unnamed semaphore with value = 0 the second value for sem_init
(..) is 1 so as it said in MAN the semaphore is shared between processes 2) creating child, child waits until semaphore value becomes 1 我以为我的程序应该像这样工作:1)初始化值为0的未命名信号量sem_init
(..)的第二个值是1,因此它在MAN中表示信号量在进程之间共享2)创建子进程,子进程等待直到信号量值变为1
parent process increases the value of semaphore so the child should exit now but it doesn't exit really, so that is the problem 父进程增加了信号量的值,因此子进程现在应该退出,但实际上并没有退出,所以这就是问题所在
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
pid_t child;
void child_proc(sem_t* sem) {
sem_wait(sem);
printf("OK\n");
}
void parent_proc(sem_t* sem) {
sem_post(sem);
sleep(2);
int status;
waitpid(child, &status, 0);
}
int main(int argc, char* argv[]) {
sem_t sem;
sem_init(&sem, 1, 0);
child = fork();
if (0 == child) {
child_proc(&sem);
return 0;
}
parent_proc(&sem);
return 0;
}
The problem is that both processes have a local (not shared) copy of the semaphore structure and changes in one process won't reflect to the other process. 问题在于,两个进程都具有信号量结构的本地(而非共享)副本,并且一个进程中的更改不会反映到另一个进程中。
As the man page also says , if you want to share semaphores across processes, not only do you need to pass a non-zero value to the second argument of sem_init
, but the sem_t
structure also needs to exist in an area of shared memory. 就像手册页中所说的那样 ,如果要在进程之间共享信号量,不仅需要将非零值传递给sem_init
的第二个参数,而且sem_t
结构也需要存在于共享内存区域中。 In your example program, it exists on the stack, which is not shared. 在您的示例程序中,它存在于堆栈中,不会共享。
You can have shared memory by using a common file mapping (with mmap
) or with shm_open
, notably. 您可以通过使用通用文件映射(带有mmap
)或shm_open
来拥有共享内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.