The Linux Programming Interface

(nextflipdebug5) #1

984 Chapter 47


Using the program in Listing 47-8, along with various others shown in this chapter,
we can study the operation of System V semaphores, as demonstrated in the follow-
ing shell session. We begin by using a program that creates a semaphore set con-
taining two semaphores, which we initialize to 1 and 0:
$ ./svsem_create -p 2
32769 ID of semaphore set
$ ./svsem_setall 32769 1 0
Semaphore values changed (PID=3658)

We don’t show the code of the svsem/svsem_create.c program in this chapter,
but it is provided in the source code distribution for this book. This program
performs the same function for semaphores as the program in Listing 46-1 (on
page 938) performs for message queues; that is, it creates a semaphore set.
The only notable difference is that svsem_create.c takes an additional argu-
ment specifying the size of the semaphore set to be created.
Next, we start three background instances of the program in Listing 47-8 to per-
form semop() operations on the semaphore set. The program prints messages
before and after each semaphore operation. These messages include the time, so
that we can see when each operation starts and when it completes, and the process
ID, so that we can track the operation of multiple instances of the program. The
first command makes a request to decrease both semaphores by 1:

$ ./svsem_op 32769 0-1,1-1 & Operation 1
3659, 16:02:05: about to semop() [0-1,1-1]
[1] 3659

In the above output, we see that the program printed a message saying that the
semop() operation is about to be performed, but did not print any further messages,
because the semop() call blocks. The call blocks because semaphore 1 has the value 0.
Next, we execute a command that makes a request to decrease semaphore 1 by 1:

$ ./svsem_op 32769 1-1 & Operation 2
3660, 16:02:22: about to semop() [1-1]
[2] 3660

This command also blocks. Next, we execute a command that waits for the value of
semaphore 0 to equal 0:

$ ./svsem_op 32769 0=0 & Operation 3
3661, 16:02:27: about to semop() [0=0]
[3] 3661

Again, this command blocks, in this case because the value of semaphore 0 is cur-
rently 1.
Now, we use the program in Listing 47-3 to inspect the semaphore set:

$ ./svsem_mon 32769
Semaphore changed: Sun Jul 25 16:01:53 2010
Last semop(): Thu Jan 1 01:00:00 1970
Sem # Value SEMPID SEMNCNT SEMZCNT
0 1 0 1 1
1 0 0 2 0
Free download pdf