0

I am trying to learn use semophores. What I am trying to do is initialize a semaphore. Then set its value to 1, get that value and print it. But every time I try to do it, it shows me -1. My code is given below. Thanks in advance.

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/sem.h>

union semun {
    int val;
    struct semid_ds *buf;
    ushort *array;
    struct seminfo *__buf;
    void *__pad;
};

int main(){
    int pid, status, semid, value;
    union semun semopts;

    semid = semget(IPC_PRIVATE, 1, IPC_CREAT);

    semopts.val = 1;
    semctl(semid, 0, SETVAL, semopts);

    value = semctl(semid, 0, GETVAL, 0);
    printf("Value  = %d\n", value);

    return 0;
}
odbhut.shei.chhele
  • 5,834
  • 16
  • 69
  • 109
  • 3
    system calls often return `-1` to indicate an error. You should check [`errno`](http://en.cppreference.com/w/c/error/errno) to see what went wrong. You can get a printable string of the error with e.g. the [`strerror`](http://en.cppreference.com/w/c/string/byte/strerror) function. – Some programmer dude Sep 25 '13 at 06:16
  • 1
    The code is missing to test the outcome of `semget()`, so it is not sure whether the value of `semid` represent a valid semephore set identifier at all. – alk Sep 25 '13 at 07:24

1 Answers1

1

The code is missing to at least grant itself read/write access to the semaphore set created.

To do so modifiy the code like this:

if (-1 == (semid = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | S_IRUSR  | S_IWUSR)))
{
  perror("semget() failed");
  exit (EXIT_FAILURE);
}
alk
  • 69,737
  • 10
  • 105
  • 255
  • I already checked that. The semaphore is being created. The problem is with the flag IPC_CREAT. Apparently IPC_CREAT doesn't give permission to set value to the semaphore. If I use 0777 instead of IPC_CREAT then it works. Thanks for the help. – odbhut.shei.chhele Sep 25 '13 at 20:52