Why can't I interact with a System V semaphores I've created?

534 Views Asked by At

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.

1

There are 1 best solutions below

0
einpoklum On

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() and semctl() functions (and maybe semtimedop(). For example, if we have:

union semun  
{
    int val;
    struct semid_ds *buf;
    ushort array [1];
} sem_attr;
int result;

defined, we can write:

sem_attr.val = 1;
result = semctl (semaphore_set_index, 0, SETVAL, sem_attr);
if (result == -1) { /* handle error here */ }

which sets the semaphore value to 1.


Notes:

  • I'm ignoring your reference to clang vs another compiler.
  • As @ThomasJager suggests - always check your API call return values for errors.
  • I'm partially basing this answer on this article:

    System V Sempaphores in Linux