Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 15.10 POSIX Semaphores 579


15.10 POSIX Semaphores


The POSIX semaphoremechanism is one of three IPC mechanisms that originated with
the real-time extensions to POSIX.1. The Single UNIX Specification placed the three
mechanisms (message queues, semaphores, and shared memory) in option classes.
Prior to SUSv4, the POSIX semaphoreinterfaces wereincluded in the semaphores
option. In SUSv4, these interfaces weremoved to the base specification, but the
message queue and shared memory interfaces remained optional.
The POSIX semaphoreinterfaces weremeant to address several deficiencies with
the XSI semaphoreinterfaces:
•The POSIX semaphoreinterfaces allow for higher-performance implementations
compared to XSI semaphores.
•The POSIX semaphoreinterfaces aresimpler to use: thereare nosemaphoresets,
and several of the interfaces arepatterned after familiar file system operations.
Although there is no requirement that they be implemented in the file system,
some systems do take this approach.
•The POSIX semaphores behave moregracefully when removed. Recall that
when an XSI semaphore is removed, operations using the same semaphore
identifier fail witherrnoset toEIDRM.With POSIX semaphores, operations
continue to work normally until the last reference to the semaphore is released.
POSIX semaphores areavailable in two flavors: named and unnamed. They differ
in how they arecreated and destroyed, but otherwise work the same. Unnamed
semaphores exist in memory only and requirethat processes have access to the memory
to be able to use the semaphores. This means they can be used only by threads in the
same process or threads in different processes that have mapped the same memory
extent into their address spaces. Named semaphores, in contrast, areaccessed by name
and can be used by threads in any processes that know their names.
To create a new named semaphore or use an existing one, we call thesem_open
function.
#include <semaphore.h>
sem_t *sem_open(const char *name,int oflag,... /* mode_tmode,
unsigned intvalue*/ );
Returns: Pointer to semaphore if OK,SEM_FAILEDon error
When using an existing named semaphore, we specify only two arguments: the name of
the semaphoreand a zerovalue for theoflagargument. When theoflagargument has
theO_CREATflag set, we create a new named semaphore if it does not yet exist. If it
already exists, it is opened for use, but no additional initialization takes place.
When we specify theO_CREATflag, we need to provide two additional arguments.
Themodeargument specifies who can access the semaphore. It can take on the same
values as the permission bits for opening a file: user-read, user-write, user-execute,
group-read, group-write, group-execute, other-read, other-write, and other-execute.
The resulting permissions assigned to the semaphoreare modified by the caller’s file
Free download pdf