Programming Interfaces Guide

Semaphore Operations

semop(2) 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 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(2) call, and is set to 10 by default.

The operation to be performed is determined as follows:

The two control flags that can be used with semop(2) are IPC_NOWAIT and SEM_UNDO.


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.


Allows individual operations in the array to be undone when the process exits.

The following code illustrates semop(2).

#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);