System V Semaphores 985
When a semaphore set is created, the sem_otime field of the associated semid_ds data
structure is initialized to 0. A calendar time value of 0 corresponds to the Epoch
(Section 10.1), and ctime() displays this as 1 AM, 1 January 1970, since the local
timezone is Central Europe, one hour ahead of UTC.
Examining the output further, we can see that, for semaphore 0, the semncnt
value is 1 because operation 1 is waiting to decrease the semaphore value, and
semzcnt is 1 because operation 3 is waiting for this semaphore to equal 0. For sema-
phore 1, the semncnt value of 2 reflects the fact that operation 1 and operation 2 are
waiting to decrease the semaphore value.
Next, we try a nonblocking operation on the semaphore set. This operation
waits for semaphore 0 to equal 0. Since this operation can’t be immediately per-
formed, semop() fails with the error EAGAIN:
$ ./svsem_op 32769 0=0n Operation 4
3673, 16:03:13: about to semop() [0=0n]
ERROR [EAGAIN/EWOULDBLOCK Resource temporarily unavailable] semop (PID=3673)
Now we add 1 to semaphore 1. This causes two of the earlier blocked operations (1
and 3) to unblock:
$ ./svsem_op 32769 1+1 Operation 5
3674, 16:03:29: about to semop() [1+1]
3659, 16:03:29: semop() completed [0-1,1-1] Operation 1 completes
3661, 16:03:29: semop() completed [0=0] Operation 3 completes
3674, 16:03:29: semop() completed [1+1] Operation 5 completes
[1] Done ./svsem_op 32769 0-1,1-1
[3]+ Done ./svsem_op 32769 0=0
When we use our monitoring program to inspect the state of the semaphore set,
we see that the sem_otime field of the associated semid_ds data structure has been
updated, and the sempid values of both semaphores have been updated. We also see
that the semncnt value for semaphore 1 is 1, since operation 2 is still blocked, wait-
ing to decrease the value of this semaphore:
$ ./svsem_mon 32769
Semaphore changed: Sun Jul 25 16:01:53 2010
Last semop(): Sun Jul 25 16:03:29 2010
Sem # Value SEMPID SEMNCNT SEMZCNT
0 0 3661 0 0
1 0 3659 1 0
From the above output, we see that the sem_otime value has been updated. We also
see that semaphore 0 was last operated on by process ID 3661 (operation 3) and
semaphore 1 was last operated on by process ID 3659 (operation 1).
Finally, we remove the semaphore set. This causes the still blocked operation 2
to fail with the error EIDRM:
$ ./svsem_rm 32769
ERROR [EIDRM Identifier removed] semop (PID=3660)
We don’t show the source code for the svsem/svsem_rm.c program in this chapter,
but it is provided in the source code distribution for this book. This program
removes the semaphore set identified by its command-line argument.