Odd / incorrect behavior of sem_getvalue semaphore in OS X

I have a very simple semaphore code that works fine on Linux but cannot make it work properly on OS X in its entire life ... It returns the strangest results ...

#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>

int main()
{
    sem_t* test;
    test = sem_open("test", O_CREAT, 0, 1);

    int value;
    sem_getvalue(test, &value);
    printf("Semaphore initialized to %d\n", value);
}

Compiling this on OS X with g ++ returns the following output:

iQudsi:Desktop mqudsi$ g++ test.cpp
iQudsi:Desktop mqudsi$ ./a.out 
Semaphore initialized to -1881139893

While on Ubuntu I get a decidedly more reasonable result:

iQudsi: Desktop mqudsi$ g++ test.cpp -lrt
iQudsi:Desktop mqudsi$ ./a.out 
Semaphore initialized to 1

I have been on this for 3 hours in a row and cannot understand why OS X returns such strange results ...

I tried to use file paths as a semaphore name, it didn't matter.

I would be grateful for any help I could receive.

+3
source share
3
$ g++ sem-testing.cc -Wall
$ ./a.out 
sem_getvalue: Function not implemented
$ man sem_getvalue
No manual entry for sem_getvalue

, Mac OS X, , , , , , , , . , int value = 0;, , , .

, ( bdonlan):

#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>

int main()
{
    sem_t* test;
    test = sem_open("test", O_CREAT, 0, 1);
    if (test == SEM_FAILED) {
        perror("sem_open");
        return 1;
    }

    int value;
    if (sem_getvalue(test, &value)) {
        perror("sem_getvalue");
        return 1;
    }
    printf("Semaphore initialized to %d\n", value);
}
+6

? :

#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>

int main()
{
    sem_t* test;
    test = sem_open("test", O_CREAT, 0, 1);
    if (test == SEM_FAILED) {
        perror("sem_open");
        return 1;
    }

    int value;
    if (sem_getvalue(test, &value)) {
        perror("sem_getvalue");
        return 1;
    }
    printf("Semaphore initialized to %d\n", value);
}
+8

, , sem_open() - .

, , OSX posix sems - /dev/shm , sem_open().

, SysV.

A similar question regarding Slackware was asked here: how-do-i-stop-semopen-failing-with-enosys

However, further search reveals that OSX semaphones are built on top of Mach semaphores, and you will probably need sem_unlink () them when you finish (and not just sem_close (), or maybe instead), and you should be careful about permissions - I suggest starting with 0777 or possibly 0700, not 0. See posiz semaphores in Darwin

+2
source

Source: https://habr.com/ru/post/1708462/


All Articles