How can I get multiple calls to sem_open working in C?

旧时模样 提交于 2019-12-04 03:37:20

Are you using the 4 parameter or 2 parameter version of sem_open?

Make sure to use the 4 parameter version and use a mode that will allow other processes to open the semaphore. Assuming all the processes are owned by the same user, a mode of 0600 (S_IRUSR | S_IWUSR) will be sufficient.

You may also want to verify that you umask is not masking out any of the necessary permissions.

Don't forget to specify the mode and value parameter when using O_CREAT in the flags. Here is a working example :

#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;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!