Semaphore Operations
semop
()
performs operations on a semaphore
set. The semid
argument is the semaphore ID
returned by a previous
semget
(2) call. The sops
argument
is a pointer to an array of structures, each containing the
following information about a semaphore operation:
-
The semaphore number
-
The operation to be performed
-
Control flags, if any
The sembuf
structure specifies a
semaphore operation, as defined in sys/sem.h
. The
nsops
argument specifies the length of the array,
the maximum size of which is determined by the
SEMOPM
configuration option. This option determines
the maximum number of operations allowed by a single
semop
()
call, and is set to 10 by default.
The operation to be performed is determined as follows:
-
Positive integer increments the semaphore value by the specified amount.
-
Negative integer decrements the semaphore value by the specified amount. An attempt to set a semaphore to a value less than zero fails or blocks, depending on whether
IPC_NOWAIT
is in effect. -
Value zero means to wait for the semaphore value to reach zero.
The two control flags that can be used
with semop
()
are IPC_NOWAIT
and
SEM_UNDO
.
-
IPC_NOWAIT
-
Can be set for any operations in the array. Makes the interface return without changing any semaphore value if it cannot perform any of the operations for which
IPC_NOWAIT
is set. The interface fails if it tries to decrement a semaphore more than its current value, or tests a nonzero semaphore to be equal to zero. -
SEM_UNDO
-
Allows individual operations in the array to be undone when the process exits.
The following code illustrates
semop
().
#include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> ... int i; /* work area */ int nsops; /* number of operations to do */ int semid; /* semid of semaphore set */ struct sembuf *sops; /* ptr to operations to perform */ ... if ((i = semop(semid, sops, nsops)) == -1) { perror("semop: semop failed"); } else (void) fprintf(stderr, "semop: returned %d\n", i); ...
For more information, see the
semop
(2) man page,