Semaphore In Os

In order to configure the semaphore in C language under Linux, I wrote the following few lines of code:

int semid = semget(1234 , 2 , IPC_CREAT | 0666);
    if(semid < 0)
        printf("ERROR in semget \n ");
        if( semctl(semid, 0, SETVAL, 1) < 0)
        {
            printf("ERROR in setting value of semaphore \n");
            exit(EXIT_FAILURE);
        }

But my software constantly displays the message: ERROR in semget ERROR in setting value of semaphore, and I’m not sure why.

when semget returns -1 it’ll also set errno. worth checking why

the key argument should be obtained by creating a file to use as the semkey and a call to ftok to return a key for it

see semget(2) - Linux manual page and ftok(3) - Linux manual page

2 Likes

No runtime error for me with your code snippet.

Tested with GCC version 12.2.1

1 Like

Related: Under Linux, also have a look at futex.

https://man7.org/linux/man-pages/man2/futex.2.html

https://eli.thegreenplace.net/2018/basics-of-futexes/

2 Likes

Well thank you for that

you are welcome mate

1 Like