15.5 Exercise: POSIX Unnamed SemaphoresThis exercise describes an implementation of POSIX:SEM-like unnamed semaphores in terms of semaphore sets. Represent the unnamed semaphore by a data structure of type mysem_t, which for this exercise is simply an int. The mysem.h header file should contain the definition of mysem_t and the prototypes for the semaphore functions.
All these functions return 0 if successful. On error, they return 1 and set errno appropriately. Actually, the last point is a little subtle. It will probably turn out that the only statements that can cause an error are the semaphore set calls and they set errno. If that is the case, the functions return the correct errno value as long as there are no intervening functions that might set errno.Assume that applications call mysem_init before creating any threads. The mysem_t value is the semaphore ID of a semaphore set. Ignore the value of pshared, since semaphore sets are sharable among processes. Use a key of IPC_PRIVATE.Implement the mysem_wait and mysem_post directly with calls to semop. The details will depend on how sem_init initializes the semaphore. Implement mysem_destroy with a call to semctl.Test your implementation with Programs 14.5 and 14.6 to see that it enforces mutual exclusion.Before logging out, use ipcs -s from the command line. If semaphores still exist (because of a program bug), delete each of them, using the following command.
This command deletes the semaphore with ID n. The semaphore should be created only once by the test program. It should also be deleted only once, not by all the children in the process chain. |