- int value;
- if ( (value=semctl(sem_id,0,GETVAL,semunion)) < 0 ) {
- perror("cannot read semaphore"); /* a <0 is an error */
- printf("on semid=%d\n",sem_id);
- exit(1);
- }
- return value;
+ return semctl(sem_id, 0, GETVAL);
+}
+/*
+ * Define sembuf structures to lock and unlock the semaphore
+ * (used to implement a mutex)
+ */
+struct sembuf sem_lock={ /* to lock semaphore */
+ 0, /* semaphore number (only one so 0) */
+ -1, /* operation (-1 to use resource) */
+ SEM_UNDO}; /* flag (set for undo at exit) */
+struct sembuf sem_ulock={ /* to unlock semaphore */
+ 0, /* semaphore number (only one so 0) */
+ 1, /* operation (1 to release resource) */
+ SEM_UNO}; /* flag (in this case 0) */
+/*
+ * Function MutexLock: to lock a mutex/semaphore
+ *
+ * Input: a semaphore id #
+ * Output: semop return code (0 OK, -1 KO)
+ */
+inline int MutexLock(int sem_id)
+{
+ return semop(sem_id, &sem_lock, 1);
+}
+/*
+ * Function MutexUnlock: to unlock a mutex/semaphore
+ *
+ * Input: a semaphore id #
+ * Return: semop return code (0 OK, -1 KO)
+ */
+inline int MutexUnlock(int sem_id)
+{
+ return semop(sem_id, &sem_ulock, 1);