15.5 Exercise: POSIX Unnamed Semaphores

Team-FLY

This 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.

 int mysem_init(mysem_t *sem, int pshared, unsigned int value); int mysem_destroy(mysem_t *sem); int mysem_wait(mysem_t *sem); int mysem_post(mysem_t *sem); 

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.

 ipcrm -s n 

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.

Team-FLY


Unix Systems Programming
UNIX Systems Programming: Communication, Concurrency and Threads
ISBN: 0130424110
EAN: 2147483647
Year: 2003
Pages: 274

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net