I'm trying to use System V semaphores in C for a lab but my courses aren't helping me.
I can create my semaphore and delete it (using semget() and semctl()), but I can't interact with it: its value always stays the same (0) and it doesn't do it's semaphore job when I ask it to (with semop()).
By the way, I extracted below the code I already wrote concerning my semaphore:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int main()
{
// some code
int sem;
struct sembuf up = {0,1,0};
struct sembuf down = {0,-1,0};
sem = semget(IPC_PRIVATE, 1, 777 | IPC_CREAT);
// Tried with 777 because why not. Originally at 600
// but it gave me a "Permission denied" error.
semop(sem, &up, 1); // up
// some critical code
semop(sem, &down, 1); // ... and down
semctl(sem, 0, IPC_RMID); // deletion
}
Does someone know what's missing in my code to make my semaphore work?
NB: No, I can't use POSIX semaphores. Yes I know that's sad.
What the
semget()function returns isn't "a semaphor", it's an id of a semaphore set (or in your case, a single semaphore, since you're creating a set of size 1). That set id will stay 0 and won't change, no matter what happens to the sempahore itself - which isn't held as a variable in your program.The interaction with the semaphore is only via the
semop()andsemctl()functions (and maybesemtimedop(). For example, if we have:defined, we can write:
which sets the semaphore value to 1.
Notes:
I'm partially basing this answer on this article:
System V Sempaphores in Linux