Programming Interfaces Guide

Controlling Semaphores

semctl(2) changes permissions and other characteristics of a semaphore set. It must be called with a valid semaphore ID. The semnum value selects a semaphore within an array by its index. The cmd argument is one of the following control flags.

GETVAL

Return the value of a single semaphore.

SETVAL

Set the value of a single semaphore. In this case, arg is taken as arg.val, an int.

GETPID

Return the PID of the process that performed the last operation on the semaphore or array.

GETNCNT

Return the number of processes waiting for the value of a semaphore to increase.

GETZCNT

Return the number of processes waiting for the value of a particular semaphore to reach zero.

GETALL

Return the values for all semaphores in a set. In this case, arg is taken as arg.array, a pointer to an array of unsigned short values.

SETALL

Set values for all semaphores in a set. In this case, arg is taken as arg.array, a pointer to an array of unsigned short values.

IPC_STAT

Return the status information from the control structure for the semaphore set and place it in the data structure pointed to by arg.buf, a pointer to a buffer of type semid_ds.

IPC_SET

Set the effective user and group identification and permissions. In this case, arg is taken as arg.buf.

IPC_RMID

Remove the specified semaphore set.

A process must have an effective user identification of owner, creator, or superuser to perform an IPC_SET or IPC_RMID command. Read and write permission is required, as for the other control commands.

The following code illustrates semctl(2).


#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
...
 	register int				i;
 ...
 	i = semctl(semid, semnum, cmd, arg);
 	if (i == –1) {
 		perror("semctl: semctl failed");
 		exit(1);
...