1 /* Function MutexCreate: create a mutex/semaphore */
2 int MutexCreate(key_t ipc_key)
4 const union semun semunion={1}; /* semaphore union structure */
6 sem_id = semget(ipc_key, 1, IPC_CREAT|0666); /* get semaphore ID */
7 if (sem_id == -1) { /* if error return code */
10 ret = semctl(sem_id, 0, SETVAL, semunion); /* init semaphore */
16 /* Function MutexFind: get the semaphore/mutex Id given the IPC key value */
17 int MutexFind(key_t ipc_key)
19 return semget(ipc_key,1,0);
21 /* Function MutexRead: read the current value of the mutex/semaphore */
22 int MutexRead(int sem_id)
24 return semctl(sem_id, 0, GETVAL);
26 /* Define sembuf structures to lock and unlock the semaphore */
27 struct sembuf sem_lock={ /* to lock semaphore */
28 0, /* semaphore number (only one so 0) */
29 -1, /* operation (-1 to use resource) */
30 SEM_UNDO}; /* flag (set for undo at exit) */
31 struct sembuf sem_ulock={ /* to unlock semaphore */
32 0, /* semaphore number (only one so 0) */
33 1, /* operation (1 to release resource) */
34 SEM_UNDO}; /* flag (in this case 0) */
35 /* Function MutexLock: to lock a mutex/semaphore */
36 int MutexLock(int sem_id)
38 return semop(sem_id, &sem_lock, 1);
40 /* Function MutexUnlock: to unlock a mutex/semaphore */
41 int MutexUnlock(int sem_id)
43 return semop(sem_id, &sem_ulock, 1);
45 /* Function MutexRemove: remove a mutex/semaphore */
46 int MutexRemove(int sem_id)
48 return semctl(sem_id, 0, IPC_RMID);