C - 信号量未在所有进程上共享

标签 c process synchronization semaphore

我正在开发一个需要进程同步的项目。我遇到的问题是我使用的 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/

相关文章:

c - 尝试消除共轭梯度内核中的 cudaDeviceSynchronize()

c - 如何使用 read 将输出通过管道传输到 C 中的另一个程序

c - fork 再次写入文件句柄

java - ProcessBuilder 持有生成进程的锁

java - 从批处理文件中终止从 Java 启动的进程

c - #ifndef 在 c 文件中?

java - 在多个 JVM 上维护单个实例

java - Java 中不同步的 getter/setter 行为

java - 如果只有一个writer线程并且没有对map进行结构修改,我们是否需要同步java HashMap gets

java - 在 Windows 机器上监控 (java) 进程死亡的最佳方法是什么?