#include <stdio.h> 
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

#define NSEMS 3
#define WAIT -1
#define SIGNAL 1

int main() {
   /*Semaphorengruppe mit NSEMS (=3) Semaphoren anlegen*/
   int id = semget(IPC_PRIVATE, NSEMS, IPC_CREAT | 0770);
   printf("Identifier der Gruppe: %i\n", id);
   
   /*Alle Semaphore der Gruppe initialisieren*/
   unsigned short init[NSEMS];
   int i;
   for(i=0; i<NSEMS; i++) {
      init[i] = 1;
   }
   semctl(id, NSEMS, SETALL, init);
   
   /*Werte der Semaphore abfragen*/
   unsigned short out[NSEMS];
   semctl(id, NSEMS, GETALL, out);
   printf("Wert des 1. und 2. Semaphors: %i, %i\n", out[0], out[1]);
   
   /*wait()/down()-Operation auf erstem Semaphor der Gruppe ausführen*/
   struct sembuf wait;
   wait.sem_num = 0;
   wait.sem_op = WAIT;
   wait.sem_flg = 0;
   
   semop(id, &wait, 1);

   /*Werte der Semaphore erneut abfragen*/
   semctl(id, NSEMS, GETALL, out);
   printf("Wert des 1. und 2. Semaphors: %i, %i\n", out[0], out[1]);
         
   /*Semaphorengruppe löschen*/
   semctl(id, NSEMS, IPC_RMID, 0);

   return EXIT_SUCCESS;
}
