Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C- Semaphore sem_getvalue not returning what I'm expecting?

Tags:

c

semaphore

I've been trying to get myself more acquainted with semaphores and was wondering why this code isn't printing the value I expect.

#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[]) {
    sem_t sem;
    sem_init(&sem, 0, 1);
    int value;
    sem_getvalue(&sem, &value);
    printf("%d\n",value);

    return 0;
}

It prints 0 for the value. But from my understanding it should be getting the value I initialized the semaphore with which is 1? I tried using a semaphore in some code with pthreads and I initialized the semaphore with a value of 1, but when I called the sem_getvalue function it was printing 32767. Am I missing something here? Thanks in advance.

Edit: sem_init and sem_getvalue both return -1

Edit: Solved. It appears unnamed semaphores aren't implemented on Mac.

like image 318
zProgrammer Avatar asked Apr 18 '14 03:04

zProgrammer


2 Answers

I'm getting the output as expected. (i.e. 1)

try using linking with pthread library

gcc sema.c -lpthread
like image 67
user207064 Avatar answered Sep 25 '22 14:09

user207064


Edit: Solved. It appears unnamed semaphores aren't implemented on Mac.

POSIX semaphore is considered as deprecated on Mac OSX. So, it doesn't work on it as expected.

like image 45
snr Avatar answered Sep 22 '22 14:09

snr