978 Chapter 47
This rather complex solution to the race problem is not required in all applica-
tions. We don’t need it if one process is guaranteed to be able to create and initialize
the semaphore before any other processes attempt to use it. This would be the
case, for example, if a parent creates and initializes the semaphore before creating
child processes with which it shares the semaphore. In such cases, it is sufficient for
the first process to follow its semget() call by a semctl() SETVAL or SETALL operation.Figure 47-2: Two processes racing to initialize the same semaphore47.6 Semaphore Operations
The semop() system call performs one or more operations on the semaphores in the
semaphore set identified by semid.First semget() succeeds
(because set didn’t exist)Process A Process Btime slice
expirestime slice
beginstime slice
beginstime slice
endsFirst semget() fails (so this
process knows set exists)Second semget() succeedsExecutes semop()semctl() initializes semaphoreExecutes semop() Executing
on CPUWaiting
for CPUKey#include <sys/types.h> /* For portability */
#include <sys/sem.h>int semop(int semid, struct sembuf *sops, unsigned int nsops);
Returns 0 on success, or –1 on error