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;
}
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);
}