Controlling Semaphores
semctl()
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,
argis taken asarg.val, anint. -
GETPID -
Return the
PIDof 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,
argis taken asarg.array, a pointer to an array ofunsigned shortvalues. -
SETALL -
Set values for all semaphores in a set. In this case,
argis taken asarg.array, a pointer to an array ofunsigned shortvalues. -
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 typesemid_ds. -
IPC_SET -
Set the effective user and group identification and permissions. In this case,
argis taken asarg.buf. -
IPC_RMID -
Remove the specified semaphore set.
A process must have a user identification of the owner, the creator, or the superuser to
perform an IPC_SET or
IPC_RMID command. For other
control commands read and write permission is
required.
The following code illustrates semctl().
#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);
...