【问题标题】:How can I get multiple calls to sem_open working in C?如何在 C 中多次调用 sem_open?
【发布时间】:2011-01-18 16:06:26
【问题描述】:

让信号量在基于 Linux 的 C 系统上工作时遇到了很多困难。

我的申请流程是这样的:

  1. 应用程序启动
  2. 应用程序分叉到子/父
  3. 每个进程都使用sem_open 和一个通用名称来打开信号量。

如果我在分叉之前创建信号量,它工作正常。但是,要求阻止我这样做。当我第二次尝试调用sem_open 时,我收到“Permission Denied”错误(通过errno)。

是否有可能以任何方式做到这一点?或者有什么办法可以在一个进程中打开信号量,并使用共享内存机制与子进程共享?

【问题讨论】:

    标签: c linux semaphore


    【解决方案1】:

    在标志中使用 O_CREAT 时不要忘记指定模式和值参数。 这是一个工作示例:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <semaphore.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <sys/wait.h>
    
    static void parent(void)
    {
        sem_t * sem_id;
        sem_id=sem_open("mysem", O_CREAT, 0600, 0);
        if(sem_id == SEM_FAILED) {
            perror("parent sem_open");
            return;
        }
        printf("waiting for child\n");
        if(sem_wait(sem_id) < 0) {
            perror("sem_wait");
        }
    }
    
    static void child(void)
    {
        sem_t * sem_id;
        sem_id=sem_open("mysem", O_CREAT, 0600, 0);
        if(sem_id == SEM_FAILED) {
            perror("child sem_open");
            return;
        }
        printf("Posting for parent\n");
        if(sem_post(sem_id) < 0) {
            perror("sem_post");
        }
    }
    
    int main(int argc, char *argv[])
    {
        pid_t pid;
        pid=fork();
        if(pid < 0) {
            perror("fork");
            exit(EXIT_FAILURE);
        }
    
        if(!pid) {
            child();    
        } else {
            int status;
            parent();
            wait(&status);
        }
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      你用的是4参数还是2参数版本的sem_open?

      确保使用 4 参数版本并使用允许其他进程打开信号量的模式。假设所有进程都归同一个用户所有,那么模式 0600 (S_IRUSR | S_IWUSR) 就足够了。

      您可能还想确认您的 umask 没有屏蔽任何必要的权限。

      【讨论】:

      • 我使用的是四参数版本,但我的权限不正确。 O_RDWR 似乎不是要使用的权限标志,尽管在我能找到的每个示例中都出现了。非常感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多