10 Semaphores

download 10 Semaphores

of 20

Transcript of 10 Semaphores

  • 7/29/2019 10 Semaphores

    1/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 1 of 20

    UNIX Programming

    "Chapter Tweleve - Semaphores, MessageQueues and Shared Memory"

    Chapter Outline

    Semaphores, Message Queues and Shared MemorySemaphores

    Semaphores DefinitionA Theoretical ExampleUNIX Semaphore FacilitiesUsing SemaphoresSemaphore Summary

    Shared MemoryOverviewShared Memory FunctionsShared Memory Summary

    Messge QueuesOverviewMessage Queue FunctionsQueue EfficiencyMessage Queue Summary

    The ApplictionIPC Status Commands

    SemaphoresShared MemoryMessge Queues

    Summary

    Lecture Notes

    Semaphores, Message Queues and Shared Memory

    We will now look at a set of Interprocess Communiction Facilities that were introducted inthe AT&T System V.2 release of UNIX.

    Semaphores

    A semaphore is a special varible that takes only whole positive numbers and upon whichonly two operations are allowed: wait and signal. They are used to ensure that a singleexecuting process has exclusive access to a resource.

    Here are the signal notations:

    Semaphore Definition

    A binary semaphore is a variable that can take only the values 0 and 1.

    The definition ofp and v are surprisingly simple. Suppose we have a semaphore variable,

    sv. The two operations are then defined as:

  • 7/29/2019 10 Semaphores

    2/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 2 of 20

    A Theoretical Example

    Supposed we have two processes proc1 and proc2, both of which need exclusive access toa database at some point in their execution.

    We define a single binary semaphore, sv, that starts with the value 1.

    The required pseudo-code is:

    Here's a diagram showing how the p and v operatons act as a gate into critical sections ofcode:

    UNIX Semaphore Facilities

    All the UNIX semaphore functions operate on arrays of general semaphores, rahter than asingle binary semaphore.

    The semaphore function definitions are:

  • 7/29/2019 10 Semaphores

    3/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 3 of 20

    semget

    The semget function creates a new semaphore or obtains the semaphore key of an existingsemaphore.

    semop

    The function semop is used for changing the value of the semaphore:

    The first parameter, sem_id, is the semaphore identifier, as returned from semget.

    The second parameter, sem_ops, is a pointer to an array of structures, each of which willhave at least the following members:

    semctl

    The semctl function allows direct control of semaphore information:

    The command parameter is the action to take and a fourth parameter, if present, is a unionsemun, which must have at least the following members:

    Here are two common values ofcommand are:

    Using Semaphores

    To experiment with semaphores, we'll use a single program, sem1.c, which we can invoke

    several times.

    We'll use an optional parameter to specify whether the program is responsible for creating

  • 7/29/2019 10 Semaphores

    4/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 4 of 20

    and destroying the semaphore.

    Try It Out - Semaphores

    1. After the#includes, the function prototypes and the global variable, we come to the mainfunction. It creates the semaphores.

    2. The we have a loop which entersa and leaves the critical section ten times.

    There, we first make a call to semaphore_p which sets the semaphore to wait.

    3. After the critical section, we call semaphore_v, setting the semaphore available.

  • 7/29/2019 10 Semaphores

    5/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 5 of 20

    4. The function set_semvalue initializes the semaphore using the SETVAL command insemctl call.

    5. The del_semvalue function has almost the same form, except the call to semctl uses thecommand IPC_RMID to remove the semaphore's ID:

    6. semaphore_p changes the semaphore by -1 (waiting):

    7. semaphore_v is identical except for setting the sem_op part of the sembufstructure to 1,so that the semaphore becomes available:

  • 7/29/2019 10 Semaphores

    6/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 6 of 20

    Here's some sample output, with two invocations of the program:

    How It Works

    The program sets up a semaphore. It then loops ten times, with pseudo-random waits in itscritical and non-critical sections.

    The critical section is guarded by calls to our senaphore_p and senaphore_v functions.

    Semaphore Summary

    Semaphores have a complex programming interface.

    Shared Memory

    Shared memory is the second of the three IPC facilities. It allows two unrelated processes toaccess the same logical memory.

    Overview

    Shared memory is a special range of addresses that is created by IPC for one process andappears in the address space of that process.

    Other processes can then 'attach' the same shared memory segment into their own addressspace.

  • 7/29/2019 10 Semaphores

    7/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 7 of 20

    Shared Memory Functions

    The functions for shared memory resemble those for semaphores:

    As with semaphores, the include files sys/types.h and sys/ipc.h are normally also requried.

    shmget

    We create shared memory using the shmget function:

    shmat

    when you first crete a shared memory segment, it's not accessible by any process.

    To enable access to the shared memory, we must attach it to the address space of a process.We do this with the shmat function:

    shmdt

    The shmdt function detaches the shared memory from the current process.

  • 7/29/2019 10 Semaphores

    8/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 8 of 20

    shmctl

    The control functions for shared memory are (thankfully) rather simpler than the morecomplex ones for semaphores:

    The shmid_ds structure has at least the following members:

    The first parameter, shm_id, is the identifier returned from shmget.

    The second parameter, command, is the action to take. It can take three values:

    Try It Out - Shared Memory

    1. Our first program is a coonsumer. After the header, a suitable MEM_SZ and a structurehave been defined.

  • 7/29/2019 10 Semaphores

    9/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 9 of 20

    2. We now make the shared memory accessible to the program:

    3. The next portion of the program assigns the shared_memory segment to shared_stuff.

    4. Lastly, the shared memory is detached and then deleted:

  • 7/29/2019 10 Semaphores

    10/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 10 of 20

    5. Our second program, shm2.c, is the producer and allows us to enter data for consumers.

  • 7/29/2019 10 Semaphores

    11/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 11 of 20

    When we run these programs, we get some sample output such as this:

    How It works

    The first program, shm1, cretes the shared memory segment and then attaches it to itsaddress space.

  • 7/29/2019 10 Semaphores

    12/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 12 of 20

    The second program, shm2, gets and sttaches the same shared memory segment. It get dataand makes it available to the other program.

    Shared Memory Summary

    Shared memory provides an efficient way of sharing and passing data between multipleprocesses.

    Message Queues

    We'll now take a look at the third and final IPC facility: message queues.

    Overview

    Message queues provide a way of sending a block of data from one process to another.

    Message Queue Functions

    The message queue function definitions are:

    msgget

    We crete and access a message queue using the msgget funciton:

    msgsnd

    The msgsnd function allows us to add a message to a message queue.

    When you're using messages, it's best to define your message structure something like this:

    msgrcv

    The msgrcv function retrieves messages from a message queue.

    msgctl

    The msgctl is similar to the control function for shared memory.

    The msqid_ds structure has at least the following members:

  • 7/29/2019 10 Semaphores

    13/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 13 of 20

    The first parameter, msqid, is the identifier returned from msgget.

    The second parameter, command, is the action to take. This can take three values.

    Try It Out - Message Queues

    1. Here's the receiver program:

    2. First, we set up the message queue:

    3. Then the messages are retrieved from the queue, until an end is encountered. Lastly, themessage queue is deleted:

  • 7/29/2019 10 Semaphores

    14/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 14 of 20

    4. Thesender program is very similar to msg1.c.

    We now have a call to msgsnd to send the entered text to queue:

  • 7/29/2019 10 Semaphores

    15/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 15 of 20

    we'll run the sender, msg2, first. Here's some sample output:

    How It Works

    The sender program creates a message queue and adds messages to the queue. The receivergets the message queue id and receives messges until the special text end is received.

    Queue Efficiency

    We can test the efficiency of message queues by strippin the two programs down to a bareminimum, and then passing 10 Mb of data between them.

    Message Queue Summary

    Message queues provide a reasonably easy and efficient way of passing data between twounrelated processes.

    The Application

    We're now in a position to modify our CD database application to use the IPC facilities that

    we've seen in this chapter.

    To convert our CD application to use IPC facilities, we only need to replace the file

  • 7/29/2019 10 Semaphores

    16/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 16 of 20

    pipe_imp.c .

    Try It Out - Revising the Server Functions

    1. First, we include the appropriate headers, declare some message queue keys and define astructure to hold our message data:

    2. Two variabless with file scope hold the two queue identifiers returned from the msggetfunction:

    3. We make the server responsible for creating both message quese:

    4. The server is also responsible for tidying up if it ever exits.

    5. The server read function reads a message of any type from the queue, and returns the datapart of the message.

  • 7/29/2019 10 Semaphores

    17/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 17 of 20

    6. Sending a response uses the client process ID that was stored in the request to address themessage:

    Try It Out - Revising the Client Functions

    1. When the client starts, it needs to find the server and client queue identifiers.

    2. As with the server,when the client ends, we set our file scope varibles to illegal values.

  • 7/29/2019 10 Semaphores

    18/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 18 of 20

    3. To send a message to the server, we store the data inside our structure.

    4. When the client retrieves a message from the server, it uses its process ID to receive onlymessages addressed to itself, ignoring any messages for other clients.

    pipe_imp.c , we need to define an extra four functions.

  • 7/29/2019 10 Semaphores

    19/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    Page 19 of 20

    IPC Status Commands

    Most UNIX systems with semaphores provide the ipcs and ipcrm commands that allow

    command line access to IPC information.

    Semaphores

    To examine the state of semaphores on the system, use the ipcs -s command. If anysemaphores are present, the output will have the form:

    You can use the ipcrm command to remove any semaphores left by programs.

    To delete the above semaphores, the command (on Linux) would be:

    Many UNIX systems would use:

    Shared Memory

    The ipcs -m and ipcrm shm (or ipcrm -q ) commands provide command lineprograms for accessing the details of shared memory).

    Here's some sample output from ipcs:

    Message Queues

    For messge queues the commands are ipcs -q and ipcrm msg (or ipcrm -q ).

    Here's some sample output from ipcs:

  • 7/29/2019 10 Semaphores

    20/20

    19-3-10 9:21 !.http://snap.nlc.dcccd.edu/learn/fuller3/chap12/chap12.html

    f

    Summary

    In this chapter we loked at three inter-process communication facilities: semaphores, sharedmemory, and message queues.

    CS 248 - UNIX Programming Web Site MenuInformation | Syllabus | Schedule | Online "Lectures" | Projects | Quizzes | Web Board

    Copyright 2001 by James L. Fuller, all rights reserved.

    http://www.tvcc.cc.or.us:8080/~cs248http://snap.nlc.dcccd.edu/learn/fuller3/Quizzes.htmhttp://snap.nlc.dcccd.edu/learn/fuller3/Projects.htmhttp://snap.nlc.dcccd.edu/learn/fuller3/Lecture.htmhttp://snap.nlc.dcccd.edu/learn/fuller3/Schedule.htmhttp://snap.nlc.dcccd.edu/learn/fuller3/Syllabus.htmhttp://snap.nlc.dcccd.edu/learn/fuller3/cs248.htm