next up previous contents Back to Operating Systems Home Page
Next: Messages Up: Semaphores Previous: Semaphores

Semaphores in System V UNIX

The System V specification of the UNIX operating system introduces semaphores among the other facilities for Inter-Process Communication (IPC). This implementation is a (rather messy) generalization of the above described scheme. Three features contribute to this unnecessary complication:

Moreover, semaphore counters are always nonnegative, a zero causing the waiting process to be put to sleepgif

A semaphore is created by the semget(3) system call, whose synopsis is:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int semget(key_t key, int nsems, int flag);
This system call returns an integer id for the semaphore (analogous to a file descriptor), or -1 in case of error.

The key argument is analogous to a file name, and is used to identify exclusively a semaphore set (and other IPC objects as well) all over the system, while the semaphore id is - like a file descriptor - known only by one process and by its siblings that inherit it through variables after a fork(). Cooperating processes wishing to access the semaphore set must use the same key, much like a file name is used to store on disk shared data by cooperating processes. A key is implemented as an integer (whose size is specified by the key_t type), and a library function called ftok() is provided for the purpose of generating meaningful keys (see its manpage).

The value of nsems specifies the number of semaphores in newly created semaphore set.

The value of flag is a bit mask obtained ORing constants that specify:

For example, to create one semaphore with key 333, readable an writable by an user and his group, you'd use a code fragment like:
int sid;
...
sid=semget((key_t)333, 1, SEM_R|SEM_W|(SEM_R>>3)|(SEM_W>>3)|IPC_CREAT);
if (sid<0) 
{
    perror(``Semaphore 333'');
    exit(1);
}
...

Once a semaphore has been created, a process accesses it either directly via its id, if its a private semaphore and the id has been inherited from a creating ancestor, or by calling semget() to get its id in exchange for the right key, much like opening an already existing file. In this case the IPC_PRIVATE and IPC_CREAT bits are not set.

Semaphore initialization and flagging are performed respectively via the semctl() and semop() system calls. Refer to their manpages for details on their usagegif


next up previous contents Back to Operating Systems Home Page
Next: Messages Up: Semaphores Previous: Semaphores

Franco Callari