Semaphores Chapter 7 from Inter-process Communications in Linux:

Slides:



Advertisements
Similar presentations
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Advertisements

CSCC69: Operating Systems
1 Handling Exceptions COSC 1567 C++ Programming Lecture 11.
Shared Memory  Creating a Shared Memory Segment Allocated in byte amounts  Shared Memory Operations Create Attach Detach  Shared Memory Control Remove.
Readers and Writers An introduction to the Linux programming interface for using UNIX semaphores.
XSI IPC Message Queues Semaphores Shared Memory. XSI IPC Each XSI IPC structure has two ways to identify it An internal (within the Kernel) non negative.
System V IPC (InterProcess Communication) Messages Queue, Shared Memory, and Semaphores.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
1 Tuesday, June 27, 2006 "If the 8086 architects had designed a car, they would have produced one with legs, to be compatible with the horse." - Anonymous.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
© 2006 RightNow Technologies, Inc. Tribute to Synchronization Jeff Elser December 11 th, 2006.
Motivation for ‘and’ Syncronization *A = 1; *B = 1; Process 1Process 2Process 3 wait(&A);wait(&A);wait(&B); wait(&B); signal(&A); signal(&B); signal(&B);
5.6.2 Thread Synchronization with Semaphores Semaphores can be used to notify other threads that events have occurred –Producer-consumer relationship Producer.
Inter Process Communication:  It is an essential aspect of process management. By allowing processes to communicate with each other: 1.We can synchronize.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
Advanced OS Chapter 3p2 Sections 3.4 / 3.5. Interrupts These enable software to respond to signals from hardware. The set of instructions to be executed.
UNIX IPC CSE 121 Spring 2003 Keith Marzullo. CSE 121 Spring 2003Review of Concurrency2 Creating a UNIX process A process is created by making an exact.
1 Concurrency: Deadlock and Starvation Chapter 6.
C++ for Engineers and Scientists Third Edition
Pointers Applications
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
Unix IPC Unix has three major IPC constructs to facilitate interaction between processes: Message Queues (this PowerPoint document) permit exchange of.
Process Description and Control Chapter 3. Major Requirements of an OS Interleave the execution of several processes to maximize processor utilization.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Semaphores. Readings r Silbershatz: Chapter 6 Mutual Exclusion in Critical Sections.
CS162B: Semaphores (and Shared Memory) Jacob T. Chan.
1 Chapter 6 Interprocess Communications. 2 Contents u Introduction u Universal IPC Facilities u System V IPC.
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Chapter 41 Processes Chapter 4. 2 Processes  Multiprogramming operating systems are built around the concept of process (also called task).  A process.
Thread Synchronization with Semaphores
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
S -1 Shared Memory. S -2 Motivation Shared memory allows two or more processes to share a given region of memory -- this is the fastest form of IPC because.
Chapter 4. INTERNAL REPRESENTATION OF FILES
1 Processes, Threads, Race Conditions & Deadlocks Operating Systems Review.
Lecture 3 Process Concepts. What is a Process? A process is the dynamic execution context of an executing program. Several processes may run concurrently,
System V IPC Provides three mechanisms for InterProcess Communication (IPC) : Messages : exchange messages with any process or server. Semaphores : allow.
1 Announcements The fixing the bug part of Lab 4’s assignment 2 is now considered extra credit. Comments for the code should be on the parts you wrote.
Nachos Project 4 Lecturer: Hao-Hua Chu TA: Chun-Po Wang (Artoo) Date: 2008/10/25.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
1 Semaphores Chapter 7 from Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date: January.
1 Shared Memory. 2  Introduction  Creating a Shared Memory Segment  Shared Memory Control  Shared Memory Operations  Using a File as Shared Memory.
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Semaphores Creating and Accessing Semaphore Sets Semaphore Operations
Interprocess Communication Bosky Agarwal CS 518. Presentation Layout Introduction Pipes FIFOs System V IPC 1.Using pipes 2.Working of pipes 3.Pipe Data.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
Chapter 13: Structures. In this chapter you will learn about: – Single structures – Arrays of structures – Structures as function arguments – Linked lists.
2.3 interprocess communcation (IPC) (especially via shared memory & controlling access to it)
UNIX Signals * POSIX-Defined Signals * Signaling Processes * Signal Mask * sigaction * kill and sigaction * alarm * Interval Timers * POSIX.1b Timers *
Chapter 11 – Pointer Variables. Declaring a Pointer Variable u Declared with data type, * and identifier type* pointer_variable; u * follows data type.
Inter Process Comunication in Linux by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
© 2006 RightNow Technologies, Inc. Synchronization September 15, 2006 These people do not actually work at RightNow.
IPC Message Queue. Data Structure msgque IP_NOUSED.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Shared Memory Dr. Yingwu Zhu. Overview System V shared memory Let multiple processes attach a segment of physical memory to their virtual address spaces,
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Chapter 6: Process Synchronization.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
Operating Systems Inter-Process Communication Shared Memory & Semaphores Moti Geva
Distributed and Parallel Processing George Wells.
UNIX AND POSIX APIs APIs – a set of application programming
Linux Interprocess Communication
Unix IPC Unix has three major IPC constructs to facilitate interaction between processes: Message Queues (this PowerPoint document) permit exchange of.
Shared Memory Dr. Yingwu Zhu.
Interprocess Communication-1
PTHREADS AND SEMAPHORES
Process Description and Control
| Website for Students | VTU -NOTES -Question Papers
UNIX AND POSIX APIs APIs – a set of application programming
Presentation transcript:

Semaphores Chapter 7 from Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date: January 13, 2003

Topics Semaphore Definition Creating and Accessing Semaphore Sets Semaphore Control Semaphore Control Details Semaphore Operations Semaphore Operation Details Deleting Semaphores

SEMAPHORES Semaphores

SEMAPHORES Semaphore Definition A semaphore is a data structure that is shared by several processes. Semaphores are most often used to synchronize operations (to avoid race conditions) when multiple processes access a common, non-shareable resource. By using semaphores, we attempt to avoid other multi-programming problems such as: Starvation Occurs when a process is habitually denied access to a resource it needs. Deadlock Occurs when two or more processes each hold a resource that the other needs while waiting for the other process to release its resource.

SEMAPHORES Semaphore Definition To indicate a process has gained access to the resource, the process decrements the semaphore. For events to progress correctly, the test and decrement operation on the semaphore must be atomic (i.e., noninterruptible/indivisible). There are two kinds of Semaphores: Binary semaphores Control access to a single resource, taking the value of 0 (resource is in use) or 1 (resource is available). Counting semaphores Control access to multiple resources, thus assuming a range of nonnegative values.

SEMAPHORES Semaphore Definition Semaphore is a nonnegative integer that is stored in the kernel. Access to the semaphore is provided by a series of semaphore system calls.

Creating and Accessing Semaphore Sets Before a semaphore set can be used, it must be created. The creation of the semaphore set generates a unique data structure that the system uses to identify and manipulate the semaphores. A conceptual arrangement of a system semaphore structure for a newly allocated set of three semaphores is shown in Figure 7.1.

Creating and Accessing Semaphore Sets Figure 7.1. Data structures for a set of three semaphores.

Creating and Accessing Semaphore Sets To create a semaphore or gain access to one that exists, the semget system call is used. (Table 7.1) Exp 7.1 : A program to create semaphores

Creating and Accessing Semaphore Sets 2 Manual Section <sys/types.h> <sys/ipc.h> <sys/sem.h> Include File(s) int semget (key_t key,intnsems,int semflg); Summary Return Sets errno Failure Success Yes -1 The semaphore identifier Table 7.1. Summary of the semget System Call

Creating and Accessing Semaphore Sets The semget system call takes three arguments: The first argument, key, is used by the system to generate a unique semaphore identifier. The second argument, nsems, is the number of semaphores in the set. The third argument, semflg, is used to specify access permission and/or special creation conditions.

Creating and Accessing Semaphore Sets If the semget system call fails, it returns a −1 and sets the value stored in errno. (Table 7.2.)

Creating and Accessing Semaphore Sets Explanation perror Message Constant # Semaphore identifier does not exist for this key, and IPC_CREAT was not set. No such file or directory EOENT 2 Insufficient system memory to allocate the semaphore set. Cannot allocate memory ENOMEM 12 Semaphore identifier exists for this key, but requested operation is not allowed by current access permissions. Permission denied EACCES 13 Semaphore identifier exists for this key, but the flags IPC_CREAT and IPC_EXCL are both set. File exists EEXIST 17 System-imposed limit (SEMMNI) for the number of semaphore sets or systemwide maximum number of semaphores (SEMMNS) has been reached. No space left on device ENOSPC 28 Specified semaphore set is marked for removal. Identifier removed EIDRM 43 Table 7.2. semget Error Messages.

SEMAPHORES Semaphore Control The semctl system call allows the user to perform a variety of generalized control operations on the system semaphore structure, on the semaphores as a set, and on individual semaphores. (Table 7.3)

Semaphore Control 2 Manual Section <sys/types.h> SEMAPHORES Semaphore Control 2 Manual Section <sys/types.h> <sys/ipc.h> <sys/sem.h> Include File(s) int semctl(int semid, int semnum, int cmd, union semun arg); Summary Return Sets errno Failure Success Yes -1 0 or the value requested Table 7.3. Summary of the semctl System Call

Semaphore Control The semctl system call takes four arguments: SEMAPHORES Semaphore Control The semctl system call takes four arguments: The first argument, semid, is a valid semaphore identifier that was returned by a previous semget system call. The second argument, semnum, is the number of semaphores in the semaphore set (array), 0 means this number (index) is not relevant. The third argument to semctl, cmd, is an integer command value. the cmd value directs semctl to take one of several control actions. Each action requires specific access permissions to the semaphore control structure.

SEMAPHORES Semaphore Control The fourth argument to semctl, arg, is a union of type semun. Given the action specified by the preceding cmd argument, the data in arg can be one of any of the following four values: An integer already was set in the val member of sem_union that used with SETVAL to indicate a change of specific value for a particular semaphore within the semaphore set. A reference to a semid_ds structure where information is returned when IPC_STAT or IPC_SET is specified. A reference to an array of type unsigned short integers; the array is used either to initialize the semaphore set or as a return location when specifying GETALL. A reference to a seminfo structure when IPC_INFO is requested.

SEMAPHORES Semaphore Control If semctl fails, it returns a value of −1 and sets errno to indicate the specific error. (Table 7.4.)

Semaphore Control Explanation perror Message Constant # SEMAPHORES Semaphore Control Explanation perror Message Constant # Value for cmd is IPC_RMID or IPC_SET and the calling process in not the owner or superuser. Operation not permitted EPERM 1 The requested operation is not allowed by the current access permissions for this process. Permission denied EACCES 13 The fourth argument to semctl contains a reference to an illegal address (the union semun may not have been declared). Bad address EFAULT 14 • The semaphore identifier is invalid. • The number of semaphores specified is less than 0 or greater than the number in the semaphore set. • The value for cmd is invalid. • The value for cmd is IPC_SET, but the value for sem_perm.uid or sem_perm.gid is invalid. Invalid argument EINVAL 22 Table 7.4. semctl Error Messages.

Semaphore Control Explanation perror Message Constant # SEMAPHORES Semaphore Control Explanation perror Message Constant # The value for cmd is SETVAL or SETALL, and the value to be assigned is greater than the system maximum or less than 0. Numerical result out of range ERANGE 34 Specified semaphore set is marked for removal. Identifier removed EIDRM 43 Table 7.4. semctl Error Messages.

Semaphore Control Details SEMAPHORES Semaphore Control Details The following cmd values cause semctl to act upon the system semaphore structure IPC_STAT Return the current values of the semid_ds structure for the indicated semaphore identifier. The returned information is stored in a user-generated structure referenced by the fourth argument to semctl. To specify IPC_STAT, the process must have read permission for the semaphore set associated with the semaphore identifier.

Semaphore Control Details SEMAPHORES Semaphore Control Details IPC_SET Modify a restricted number of members in the semid_ds structure. The members sem_perm.uid, sem_perm.gid and sem_perm.mode can be changed if the effective ID of the accessing process is that of the superuser or is the same as the ID value stored in sem_perm.cuid or sem_perm.uid. To make these changes, a structure of the type semid_ds must be allocated. The appropriate members' values are then assigned, and a reference to the modified structure is passed as the fourth argument to the semctl system call. IPC_RMID Remove the semaphore set associated with the semaphore identifier.

Semaphore Control Details SEMAPHORES Semaphore Control Details The following cmd values cause semctl to act upon the entire set of semaphores: GETALL Return the current values of the semaphore set. The values are returned via the array reference passed as the fourth argument to semctl. The user is responsible for allocating the array of the proper size and type prior to passing its address to semctl. Read permission for the semaphore set is required to specify GETALL. When specifying GETALL, the argument semnum is ignored.

Semaphore Control Details SEMAPHORES Semaphore Control Details SETALL Initialize all semaphores in a set to the values stored in the array referenced by the fourth argument to semctl. Again, the user must allocate the initializing array and assign values prior to passing the address of the array to semctl. The process must have alter access for the semaphore set to use SETALL. When specifying SETALL, the sem_ctime member of the system semaphore data structure is updated.

Semaphore Control Details SEMAPHORES Semaphore Control Details The last set of semctl cmd values acts upon individual semaphores or upon specific members in the semid_ds structure. All of these commands require read permission except for SETVAL, which requires alter permission: GETVAL Return the current value of the individual semaphore referenced by the value of the semnum argument. SETVAL Set the value of the individual semaphore referenced by the semnum argument to the value specified by the fourth argument to semctl.

Semaphore Control Details SEMAPHORES Semaphore Control Details GETPID Return the PID from the sem_perm structure within the semid_ds structure. GETNCNT Return the number of processes waiting for the semaphore referenced by the semnum argument to increase in value. GETZCNT Return the number of processes waiting for the semaphore referenced by the semnum argument to become 0.

SEMAPHORES Semaphore Operations Additional operations on individual semaphores are accomplished by using the semop system call. (Table 7.5.)

Semaphore Operations 2 Manual Section <sys/types.h> SEMAPHORES Semaphore Operations 2 Manual Section <sys/types.h> <sys/ipc.h> <sys/sem.h> Include File(s) int semop(int semid, struct sembuf *sops, unsigned nsops); Summary Return Sets errno Failure Success Yes -1 Table 7.5. Summary of the semop System Call

Semaphore Operations The semop system call takes three arguments: SEMAPHORES Semaphore Operations The semop system call takes three arguments: The first argument, semid, is a valid semaphore identifier that was returned by a previous successful semget system call. The second argument, sops, is a reference to the base address of an array of semaphore operations that will be performed on the semaphore set associated with by the semid value. The third argument, nsops, is the number of elements in the array of semaphore operations.

SEMAPHORES Semaphore Operations If semop fails, it returns a value of −1 and sets errno to indicate the specific error. (Table 7.9.)

Semaphore Operations Explanation perror Message Constant # SEMAPHORES Semaphore Operations Explanation perror Message Constant # While in a wait queue for the semaphore, a signal was received by the calling process. Interrupted system call EINTR 4 The value for nsops is greater than the system limit. Argument list too long E2BIG 7 The requested operation would cause the calling process to block, but IPC_NOWAIT was specified. Resource temporarily unavailable EAGAIN 11 The limit for number of processes requesting SEM_UNDO has been exceeded. Cannot allocate memory ENOMEM 12 The requested operation is forbidden by the current access permissions. Permission denied EACCES 13 The value for sops references an illegal address. Bad address EFAULT 14 • The semaphore identifier is invalid. • The number of semaphores requesting SEM_UNDO is greater than the system limit. Invalid argument EINVAL 22 Table 7.9. semop Error Messages.

Semaphore Operations Explanation perror Message Constant # SEMAPHORES Semaphore Operations Explanation perror Message Constant # The value for sem_num is < 0 or >= to the number of semaphores in the set. File too large EFBIG 27 The requested operation would cause the system semaphore adjustment value to exceed its limit. Numerical result out of range ERANGE 34 The semaphore set associated with semid value has been removed. Identifier removed EIDRM 43 Table 7.9. semop Error Messages.

Semaphore Operation Details SEMAPHORES Semaphore Operation Details When the sem_op value is negative, the process specifying the operation is attempting to decrement the semaphore. The decrement of the semaphore is used to record the acquisition of the resource affiliated with the semaphore. When a semaphore value is to be modified, the accessing process must have alter permission for the semaphore set. (Table 7.6.)

Semaphore Operation Details SEMAPHORES Semaphore Operation Details Action Taken by semop Flag Set Condition Subtract abs(sem_op) from semval. semval >= abs(semop) Subtract abs(sem_op) from semval and update the undo counter for the semaphore. SEM_UNDO Increment semncnt for the semaphore and wait (block) until • semval >= abs(semop), then adjust semncnt and subtract as noted in the previous two rows of table. • semid is removed, then return −1 and set errno to EIDRM. • A signal is caught, then adjust semncnt and set errno to EINTR. semval < abs(semop) Return −1 immediately and set errno to EAGAIN. IPC_NOWAIT Table 7.6. Actions Taken by semop when the Value for sem_op is Negative.

Semaphore Operation Details SEMAPHORES Semaphore Operation Details When the sem_op value is positive, the process is adding to the semaphore value. The addition is used to record the return (release) of the resource affiliated with the semaphore. Again, when a semaphore value is to be modified, the accessing process must have alter permission for the semaphore set. (Table 7.7.)

Semaphore Operation Details SEMAPHORES Semaphore Operation Details Action Taken by semop Flag Set Condition Add sem_op to semval. Add sem_op to semval and update the undo counter for the semaphore. SEM_UNDO Table 7.7. Actions Taken by semop when the Value for sem_op is Positive.

Semaphore Operation Details SEMAPHORES Semaphore Operation Details When the sem_op value is zero, the process is testing the semaphore to determine if it is at 0. When a semaphore is at 0, the testing process can assume that all the resources affiliated with the semaphore are currently allocated (in use). For a semaphore value to be tested, the accessing process must have read permission for the semaphore set. (Table 7.8.)

Semaphore Operation Details SEMAPHORES Semaphore Operation Details Action Taken by semop Flag Set Condition Return immediately. semval == 0 Return −1 immediately and set errno to EAGAIN. IPC_NOWAIT semval != 0 Increment semzcnt for the semaphore and wait (block) until • semval == 0, then adjust semzcnt and return. • semid is removed, then return −1 and set errno to EIDRM. • A signal is caught, then adjust semzcnt and set errno to EINTR. Table 7.8. Actions Taken by semop when the Value for sem_op is Zero.

SEMAPHORES Deleting Semaphores The semctl command with IPC_RMID removes the semaphore in the program The command "ipcs -s" will list all semaphores on a system. The command "ipcrm -s {semid}" will delete a semaphore on system promt. To delete all semaphores you have authority over, you can use this on system; for semid in `ipcs -s | cut -d\ -f2`; do ipcrm -s $semid; done Exp 7.2 , Exp 7.3: See these header files which contain all the semaphore system calls discussed so far.