#include "sem.h" void P(int semID) { struct sembuf lock = {0, -1, 0}; if (semop(semID, &lock, 1) < 0) { perror("P"); exit(EXIT_FAILURE); } } void V(int semID) { struct sembuf unlock = {0, 1, 0}; if (semop(semID, &unlock, 1) < 0) { perror("V"); exit(EXIT_FAILURE); } } int sem_create(int key) { int semID; if ((semID = semget(key, 1, IPC_CREAT | IPC_EXCL | 0600)) < 0) { return sem_open(key); } else { arg.val = 1; if (semctl(semID, 0, SETVAL, arg) < 0) { perror("sem_create"); exit(EXIT_FAILURE); } } return semID; } void sem_delete(int semID) { if (semctl(semID, 0, IPC_RMID, NULL) < 0) { perror("sem_delete"); exit(EXIT_FAILURE); } } int sem_open(int key) { int semID; if ((semID = semget(key, 1, 0)) < 0) { perror("sem_open"); exit(EXIT_FAILURE); } return semID; } int sem_read(int semID) { int value; if ((value = semctl(semID, 0, GETVAL, NULL)) < 0) { perror("sem_read"); exit(EXIT_FAILURE); } return value; }