我正在开发一个需要进程同步的项目。我遇到的问题是我使用的 samaphore 似乎并未在所有进程之间共享。它的行为类似于局部变量。这是一个简化的代码,但演示了同样的问题:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <semaphore.h>
#include <fcntl.h>
sem_t sem_1; //Global variable (semaphore).
int main(){
sem_init(&sem_1, 1, 0); //semaphore starts with 0
pid_t child_pid_or_zero = fork(); //process fork
if (child_pid_or_zero < 0){
perror("fork() error");
exit (2);
}
if (child_pid_or_zero != 0){
sem_wait(&sem_1); //decrement to -1 and waits
printf("I am the parent %d, my child is %d.\n",getpid(),child_pid_or_zero);
}else{
printf("i am child\n");
sem_post(&sem_1); //increments
}
return 0;
}
父进程永远不会克服等待信号。我尝试向两个进程添加多个 sem_post() 并使用 sem_getvalue() 打印值,打印的数字似乎不共享(每个进程都增加自己的信号量)。
感谢您的帮助。
最佳答案
POSIX 不太清楚 sem_init
的 pshared 参数(第二个参数)是如何工作的。 Linux 手册页对此进行了更好的解释:
If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory
分配该内存并将信号量放在那里是您的责任。这不是系统会为您做的事情。
关于C - 信号量未在所有进程上共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36645758/