1 /*****************************************************************************
3 * File Mutex.c: define a set of functions for mutex manipulation
5 * Author: S. Piccardi Dec. 2002
7 * $Id: Mutex.c,v 1.1 2002/12/03 11:06:05 piccardi Exp $
9 *****************************************************************************/
10 #include <sys/sem.h> /* IPC semaphore declarations */
11 #include <sys/types.h>
14 #include <signal.h> /* signal handling declarations */
18 * Function MutexCreate: create a mutex/semaphore
20 * First call create a semaphore, using the given key.
21 * We want only one semaphore so we set second argument to 1; third
22 * parameter is the flag argument, and is set to create a semaphore
23 * with R/W privilege for the user.
24 * Second call initialize the semaphore to 1 (unlocked)
26 * Input: an IPC key value (to create an unique semaphore)
27 * Return: the semaphore id# or -1 on error
29 int MutexCreate(key_t ipc_key)
31 const union semun semunion={1}; /* semaphore union structure */
33 sem_id = semget(ipc_key, 1, IPC_CREAT|0666); /* get semaphore ID */
34 if (sem_id == -1) { /* if error return code */
37 ret = semctl(sem_id, 0, SETVAL, semunion); /* init semaphore */
44 * Function MutexFind: get the semaphore/mutex Id given the IPC key value
46 * Input: an IPC key value
48 int MutexFind(key_t ipc_key)
50 return semget(ipc_key,1,0);
53 * Function MutexRead: read the current value of the mutex/semaphore
55 * Input: a semaphore id #
56 * Return: the semaphore value
58 int MutexRead(int sem_id)
60 return semctl(sem_id, 0, GETVAL);
63 * Define sembuf structures to lock and unlock the semaphore
64 * (used to implement a mutex)
66 struct sembuf sem_lock={ /* to lock semaphore */
67 0, /* semaphore number (only one so 0) */
68 -1, /* operation (-1 to use resource) */
69 SEM_UNDO}; /* flag (set for undo at exit) */
70 struct sembuf sem_ulock={ /* to unlock semaphore */
71 0, /* semaphore number (only one so 0) */
72 1, /* operation (1 to release resource) */
73 SEM_UNDO}; /* flag (in this case 0) */
75 * Function MutexLock: to lock a mutex/semaphore
77 * Input: a semaphore id #
78 * Output: semop return code (0 OK, -1 KO)
80 int MutexLock(int sem_id)
82 return semop(sem_id, &sem_lock, 1);
85 * Function MutexUnlock: to unlock a mutex/semaphore
87 * Input: a semaphore id #
88 * Return: semop return code (0 OK, -1 KO)
90 int MutexUnlock(int sem_id)
92 return semop(sem_id, &sem_ulock, 1);