Page 286 - DCAP403_Operating System
P. 286
Unit 13: Case Study: Linux
Figure 13.10: System V IPC Semaphores Notes
Say you had many cooperating processes reading records from and writing records to a single
data file. You would want that file access to be strictly coordinated. You could use a semaphore
with an initial value of 1 and, around the file operating code, put two semaphore operations, the
first to test and decrement the semaphore’s value and the second to test and increment it. The fi rst
process to access the file would try to decrement the semaphore’s value and it would succeed,
the semaphore’s value now being 0. This process can now go ahead and use the data file but if
another process wishing to use it now tries to decrement the semaphore’s value it would fail as
the result would be -1. That process will be suspended until the first process has finished with the
data file. When the first process has finished with the data file it will increment the semaphore’s
value, making it 1 again. Now the waiting process can be woken and this time its attempt to
increment the semaphore will succeed.
System V IPC semaphore objects each describe a semaphore array and Linux uses the semid_ds
data structure to represent this. All of the semid_ds data structures in the system are pointed
at by the smeary, a vector of pointers. There are sem_nsems in each semaphore array, each one
described by a sem data structure pointed at by sem_base. All of the processes that are allowed to
manipulate the semaphore array of a System V IPC semaphore object may make system calls that
perform operations on them. The system call can specify many operations and each operation
is described by three inputs; the semaphore index, the operation value and a set of fl ags. The
semaphore index is an index into the semaphore array and the operation value is a numerical
value that will be added to the current value of the semaphore. First Linux tests whether or not
all of the operations would succeed. An operation will succeed if the operation value added to
the semaphore’s current value would be greater than zero or if both the operation value and the
semaphore’s current value are zero. If any of the semaphore operations would fail Linux may
suspend the process but only if the operation flags have not requested that the system call is
non-blocking. If the process is to be suspended then Linux must save the state of the semaphore
operations to be performed and put the current process onto a wait queue. It does this by building
a sem_queue data structure on the stack and filling it out. The new sem_queue data structure is
put at the end of this semaphore object’s wait queue (using the sem_pending and sem_pending_
LOVELY PROFESSIONAL UNIVERSITY 279