Search code examples
cipcsemaphoreposix-api

Opening a semaphore return 0


char* cath="/cath";
char* cathFlag="/cathf";
char* hyp="/hyp";
char* hypFlag="/hypf";

printf("SEMS OPEN\n");
sem_t *csem = sem_open(cath, O_CREAT, 0777, 0);
printf("CSEM: %d\n", *csem);
perror("ERROR: ");
sem_t *cfsem = sem_open(cathFlag, O_CREAT, 0777, 0);
sem_t *hsem = sem_open(hyp, O_CREAT, 0777, 0);
sem_t *hfsem = sem_open(hypFlag, O_CREAT, 0777, 0); 
printf("SEMS OPENED\n");

sem_open returns 0, perror writes Success, the semaphore does't open. Having looked through sem_overview, I saw that the problem might be in the name without a slash in the beginning, the addition did not help. There is no access to the semaphore, when sem_post is called shell abort process with a segmentation fault takes off. Help me understand what the problem is. EDIT: If i reboot system(and clean semaphores?), perror returns "No such file or directory", but after returns "Success".


Solution

  • Here is what I tried and it works :

    #include <fcntl.h>           /* For O_* constants */
    #include <sys/stat.h>        /* For mode constants */
    #include <semaphore.h>
    #include <stdio.h>
    
    
    int main(void)
    {
    
    char* cath="/cath";
    char* cathFlag="/cathf";
    char* hyp="/hyp";
    char* hypFlag="/hypf";
    
    printf("SEMS OPEN\n");
    sem_t *csem = sem_open(cath, O_CREAT, 0777, 0);
    //perror("ERROR: ");
    sem_t *cfsem = sem_open(cathFlag, O_CREAT, 0777, 0);
    sem_t *hsem = sem_open(hyp, O_CREAT, 0777, 0);
    sem_t *hfsem = sem_open(hypFlag, O_CREAT, 0777, 0); 
    printf("SEMS OPENED\n");
    
    }
    

    I compiled it:

    $ gcc tsem.c -l pthread
    

    I run it:

    $ ./a.out
    SEMS OPEN
    SEMS OPENED
    

    I looked at /dev/shm:

    $ ls /dev/shm
    sem.cath  sem.cathf  sem.hyp  sem.hypf