System Interface 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 is 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 shown below:


Can be set for any operations in the array. Makes the function return without changing any semaphore value if any operation for which IPC_NOWAIT is set cannot be performed. The function 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 the semop(2) function:

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