Initializing a Semaphore Set
semget
()
initializes or gains access to a semaphore.
When the call succeeds, it returns the semaphore ID
(semid
). The key argument is a value associated
with the semaphore ID. The nsems
argument specifies
the number of elements in a semaphore array. The call fails when
nsems
is greater than the number of elements in an
existing array. When the correct count is not known, supplying 0 for
this argument ensures that it will succeed. The
semflg
argument specifies the initial access
permissions and creation control flags. For more information, see the
semget
(2) man page.
The SEMMNI
system configuration option determines
the maximum number of semaphore arrays allowed. The SEMMNS
option
determines the maximum possible number of individual semaphores across all
semaphore sets. Because of fragmentation between semaphore sets, allocating
all available semaphores might not be possible.
The following code illustrates semget
().
#include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> ... key_t key; /* key to pass to semget() */ int semflg; /* semflg to pass to semget() */ int nsems; /* nsems to pass to semget() */ int semid; /* return value from semget() */ ... key = ... nsems = ... semflg = ... ... if ((semid = semget(key, nsems, semflg)) == -1) { perror("semget: semget failed"); exit(1); } else exit(0); ...