ptg10805159
582 Interprocess Communication Chapter 15
#include <semaphore.h>
int sem_post(sem_t *sem);
Returns: 0 if OK,−1 on error
If a process is blocked in a call tosem_wait(orsem_timedwait)when we call
sem_post,the process is awakened and the semaphorecount that was just
incremented bysem_postis decremented bysem_wait(orsem_timedwait).
When we want to use POSIX semaphores within a single process, it is easier to use
unnamed semaphores. This only changes the way we create and destroy the
semaphore. Tocreate an unnamed semaphore, we call thesem_initfunction.
#include <semaphore.h>
int sem_init(sem_t *sem,intpshared,unsigned int value);
Returns: 0 if OK,−1 on error
The pshared argument indicates if we plan to use the semaphorewith multiple
processes. If so, we set it to a nonzerovalue. Thevalueargument specifies the initial
value of the semaphore.
Instead of returning a pointer to the semaphorelikesem_opendoes, we need to
declareavariable of typesem_tand pass its address tosem_initfor initialization. If
we plan to use the semaphorebetween two processes, we need to ensurethat thesem
argument points into the memory extent that is shared between the processes.
When we aredone using the unnamed semaphore, we can discard it bycalling the
sem_destroyfunction.
#include <semaphore.h>
int sem_destroy(sem_t *sem);
Returns: 0 if OK,−1 on error
After callingsem_destroy, we can’t use any of the semaphorefunctions withsem
unless we reinitialize it by callingsem_initagain.
One other function is available to allow us to retrieve the value of a semaphore. We
call thesem_getvaluefunction for this purpose.
#include <semaphore.h>
int sem_getvalue(sem_t *restrictsem,int *restrictvalp);
Returns: 0 if OK,−1 on error
On success, the integer pointed to by thevalpargument will contain the value of the
semaphore. Be aware, however,that the value of the semaphorecan change by the time
that we try to use the value we just read. Unless we use additional synchronization
mechanisms to avoid this race, the sem_getvalue function is useful only for
debugging.
Thesem_getvaluefunction is not supported by Mac OS X 10.6.8.