Creating or Opening a Semaphore Set

The semget() system call creates a new semaphore set or obtains the identifier of an existing set.

#include <sys/types.h>        /* For portability */
#include <sys/sem.h>

int semget(key_t key, int nsems, int semflg);

Note

Returns semaphore set identifier on success, or -1 on error

The key argument is a key generated using one of the methods described in IPC Keys (i.e., usually the value IPC_PRIVATE or a key returned by ftok()).

If we are using semget() to create a new semaphore set, then nsems specifies the number of semaphores in that set, and must be greater than 0. If we are using semget() to obtain the identifier of an existing set, then nsems must be less than or equal to the size of the set (or the error EINVAL results). It is not possible to change the number of semaphores in an existing set.

The semflg argument is a bit mask specifying the permissions to be placed on a new semaphore set or checked against an existing set. These permissions are specified in the same manner as for files (Table 15-4, in Permissions on Regular Files). In addition, zero or more of the following flags can be ORed (|) in semflg to control the operation of semget():

IPC_CREAT

If no semaphore set with the specified key exists, create a new set.

IPC_EXCL

If IPC_CREAT was also specified, and a semaphore set with the specified key already exists, fail with the error EEXIST.

These flags are described in more detail in Section 45.1.

On success, semget() returns the identifier for the new or existing semaphore set. Subsequent system calls referring to individual semaphores must specify both the semaphore set identifier and the number of the semaphore within that set. The semaphores within a set are numbered starting at 0.