CS162B: Semaphores (and Shared Memory) Jacob T. Chan.

Slides:



Advertisements
Similar presentations
Florida State UniversityCOP5570 – Advanced Unix Programming IPC mechanisms Pipes Sockets System V IPC –Message Queues –Semaphores –Shared Memory.
Advertisements

More on Processes Chapter 3. Process image _the physical representation of a process in the OS _an address space consisting of code, data and stack segments.
Concurrency: Deadlock and Starvation Chapter 6. Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate.
Module R2 CS450. Next Week R1 is due next Friday ▫Bring manuals in a binder - make sure to have a cover page with group number, module, and date. You.
CSCC69: Operating Systems
Chapter 6 Process Synchronization Bernard Chen Spring 2007.
Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores.
©2009 Operačné systémy Procesy. 3.2 ©2009 Operačné systémy Process in Memory.
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.
Inter-process communication (IPC) using Shared Memory & Named Pipes CSE 5520/4520 Wireless Networks.
CS162B: POSIX Threads Jacob Chan. Objectives ▪ Review on fork() and exec() – Some issues on forking and exec-ing ▪ POSIX Threads ▪ Lab 8.
System V IPC (InterProcess Communication) Messages Queue, Shared Memory, and Semaphores.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
Chapter 10.
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.
Concurrent Processes Lecture 5. Introduction Modern operating systems can handle more than one process at a time System scheduler manages processes and.
Page 1 Processes and Threads Chapter Processes 2.2 Threads 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling.
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.
Home: Phones OFF Please Unix Kernel Parminder Singh Kang Home:
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.
Chapter 11 Operating Systems
A. Frank - P. Weisberg Operating Systems Introduction to Cooperating Processes.
I/O Systems ◦ Operating Systems ◦ CS550. Note:  Based on Operating Systems Concepts by Silberschatz, Galvin, and Gagne  Strongly recommended to read.
University of Washington CSE 351 : The Hardware/Software Interface Section 5 Structs as parameters, buffer overflows, and lab 3.
CS162B: Assembly and C Jacob T. Chan. Objectives ▪ System calls ▪ Relation of System calls to Assembly and C ▪ Special System Calls (exit, write, print,
1 Chapter 6 Interprocess Communications. 2 Contents u Introduction u Universal IPC Facilities u System V IPC.
Inter-Process Communication Mechanisms CSE331 Operating Systems Design.
Nachos Phase 1 Code -Hints and Comments
CS162B: Forking Jacob T. Chan. Fork  Forks are:  Implement with two or more prongs that is used for taking up or digging  Division into branches or.
Thread Synchronization with Semaphores
CS162B: IPv4 Socketing Jacob T. Chan. Socketing in the Real World  Most computer games are multiplayer in nature or have multiplayer components  DotA,
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
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.
June-Hyun, Moon Computer Communications LAB., Kwangwoon University Chapter 26 - Threads.
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.
TANNENBAUM SECTION 2.3 INTERPROCESS COMMUNICATION2 OPERATING SYSTEMS.
CS162B: Pipes Jacob T. Chan. Pipes  These allow output of one process to be the input of another process  One of the oldest and most basic forms of.
Florida State UniversityCOP5570 – Advanced Unix Programming Today’s topics System V Interprocess communication (IPC) mechanisms –Message Queues –Semaphores.
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.
CE Operating Systems Lecture 13 Linux/Unix interprocess communication.
Semaphores Creating and Accessing Semaphore Sets Semaphore Operations
IPC Programming. Process Model Processes can be organized into a parent-child hierarchy. Consider the following example code: /* */
2.3 interprocess communcation (IPC) (especially via shared memory & controlling access to it)
Semaphores Chapter 7 from Inter-process Communications in Linux:
© 2006 RightNow Technologies, Inc. Synchronization September 15, 2006 These people do not actually work at RightNow.
Lecture 6: Monitors & Semaphores. Monitor Contains data and procedures needed to allocate shared resources Accessible only within the monitor No way for.
Chapter 7 - Interprocess Communication Patterns
Operating Systems CMPSC 473 Signals, Introduction to mutual exclusion September 28, Lecture 9 Instructor: Bhuvan Urgaonkar.
Shared Memory Dr. Yingwu Zhu. Overview System V shared memory Let multiple processes attach a segment of physical memory to their virtual address spaces,
Introduction Contain two or more CPU share common memory and peripherals. Provide greater system throughput. Multiple processor executing simultaneous.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
Distributed and Parallel Processing George Wells.
Multithreading Tutorial
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
PTHREADS AND SEMAPHORES
Multithreading Tutorial
Process Description and Control
Concurrency: Mutual Exclusion and Process Synchronization
Multithreading Tutorial
Process Description and Control
Multithreading Tutorial
Chapter 2 Processes and Threads 2.1 Processes 2.2 Threads
CSE 451 Section 1/27/2000.
Presentation transcript:

CS162B: Semaphores (and Shared Memory) Jacob T. Chan

Pthreads: The Problem  It is not readily available in all systems  Windows doesn’t have it  Pthreads only work in the program they are in  It won’t work outside of its program  It does not deal with two different programs  What if you have two different programs that need to communicate with one another?  Files are okay and useful, but risky (file permissions and overwrites, which lead to RACE CONDITIONS)  Objective: ensure that other shared resources are not accessed simultaneously

Semaphores and Shared Memory  No need to invoke libraries (no more –lpthread)  Use the following headers:  #include  These headers should be present in any semaphore-shared memory related operation/s

Semaphore  System of visual signaling that uses flags held in both hands  Shared resource  An integer that operates on multiple processes via queue-like system  With simultaneous operations running arbitrarily  Includes rest of data that allows facilitates such operations

Implementing Semaphores int semid; // need to remember this int key = A_LARGE_CONSTANT; // ex int n = 1; // or another number semid = semget(key, n, IPC_CREAT | 0666);  1 key = 1 semaphore *array*  n = number of elements in the array; if n > existing array size, then it will result in failure.  last argument indicates flags and permissions.  IPC_CREAT = create if necessary  0666 = complete access for everyone (equivalent to chmod 777)  Returns-1 on error. Otherwise, it returns a semaphore ID

More on semget()  You can use the same key for different programs  This will return the same semaphore array  At least you won’t use different keys for different arrays  BUT, it is risky  You might be using a key that is already in use by another unrelated program  Example: running central servers (with the same port, but we aren’t discussing network socketing YET)

Accessing Semaphores struct sembuf sema[2]; // perform 2 operations  [0]: operation to wait for semaphore to become 0 (block if another process or thread is accessing the semaphore)  [1]: operation to increment semaphore int opNum = 2; // like I said, perform 2 operations

Accessing Semaphores sema[0].sem_num = 0; // index of 1st element in array sema[0].sem_op = 0; // wait if semaphore != 0 sema[0].sem_flg = SEM_UNDO; //allocate space for undo operation sema[1].sem_num = 0; sema[1].sem_op = 1; // increment semaphore by 1 sema[1].sem_flg = SEM_UNDO | IPC_NOWAIT;  If same sem_num, it means that you operate on SAME semaphore in array (which is the usual thing)

Accessing Semaphores int opResult = semop(semid, sema, opNum);  Will return -1 on error.  SEM_UNDO = Allocate space for an undo operation if process terminates abnormally.  Prevents semaphores to be locked forever (until the system reboots)  IPC_NOWAIT = Force error if operation must wait.  Although sema has 2 elements, opNum can be set to 1 if you ONLY need the 1st operation performed (the wait and get blocked operation)

Accessing Semaphores  If sema[0] is run, calling process blocks if semaphore is NOT 0  Implication: another process/thread has control over the semaphore  It will not block if semaphore is 0 already  Reason: remember it’s the waiting operation?  If it is not blocked anymore, sema[1] will be performed next  Semaphore is increased and semop() returns  If semop() returns a value that is not -1, then the process has gained control!

After the access…  Do what you want to do!  The process shared has access already to the shared memory that semaphore was guarding  Obviously, SHARED resource is involved, so after the process does its thing, it must release the resource (otherwise, a deadlock occurs)  Illustration: Using an object you just borrowed

The Release opNum = 1; // perform 1 operation sema[0].sem_num = 0; // index of 1st element in array sema[0].sem_op = -1; // decrement semaphore by 1 sema[0].sem_flg = SEM_UNDO | IPC_NOWAIT; opResult = semop(semid, sema, opNum);  Note: There are many other ways to indicate control of a semaphore.

The Release  After releasing, the other process that were waiting for it can now gain control of it  But what is that resource that the semaphore needs to protect?

Shared Memory  Shared resource that can be accessed like a string (array of characters)  Does not make the actual file, but only the string themselves  This is stored in a shared memory (hence, the name)

Initializing Shared Memory int shmid; int key = A_LARGE_CONSTANT; // ex int size = ANOTHER_CONSTANT; //preferably a power of 2 shmid = shmget(key, size, IPC_CREAT | 0666);  1 key = 1 shared memory segment  size = size of segment to be read  Will return -1 on error.

Using Same Keys  Just like semaphores, you can use same key for a different program  This way, calling shmget() will return the same memory segment  But there is also that same risk that the key is used by another unrelated program (especially true when running a central server), which is the same as your semaphores

Accessing Shared Memory #include // for strcpy char *sharedMem; char *buffer;  buffer is character array with fixed size sharedMem = shmat(shmid, NULL, 0);  Will return -1 on error.  Use if((int) sharedMem == -1) to check if shared memory is not allocated

Reading/Writing to Shared Memory  Writing to memory using strcpy (char *destination, char *source); strcpy(sharedMem, buffer);  Writing from memory using strcpy (char *destination, char *source); strcpy(buffer, sharedMem);  Note: Data written in shared memory or the buffer to be read is ASSUMED to end in ‘\0’ because otherwise, there will be a segmentation fault

Inter-Process Communication  When semaphores and shared memory is used, there is inter-process communication  Works like pipes, except that they take turns in writing and reading to shared memory  Summary:  Initialize shared resources (semaphore and shared memory)  Gain control of semaphore  Access shared memory  Release semaphore

Illustration (Application)  Using the toilet when taking a dump  Going to the barber shop  And many more… these are just some real-life illustrations of semaphores and shared memory

Lab 10: producer.c and consumer.c  Create two c programs, named producer.c and consumer.c, that does the following:  producer.c will be run on the command line using a key provided by the user. The other program, consumer.c, will run also, using this key.  NOTE: Key is supposed to be unique. To check if a semaphore key is already taken, use the ipcs command.  The command ipcs displays all the semaphore keys that are currently in use by shared memory, semaphores, and message queues. Use this for your consumer and producer programs  The producer.c program will be invoked as follows:./producer key filename

Lab 10: producer.c and consumer.c  The key will represent the key to be used for writing in the shared memory, while the filename is the name of the file that is to be written to shared memory  The writing to shared memory will only happen on a per block basis (1 block = 4096 bytes)  Accessing the producer and consumer must be synchronized using a semaphore set (so there should be a semaphore set included!)  This is to ensure that the producer will only write data to shared memory if consumer consumes data (like for example, if a block is already consumed, only will the producer produce)  Use semget() to create a new semaphore in the semaphore set

Lab 10: producer.c and consumer.c  The shared memory must be organized as follows: char data[4096]; int size; //size written to shared memory  Producer allocates the shared memory using the system call shmget()  This returns an int address location, which will be used for using shmat()  The shared memory can be written to or read from after its address is obtained using shmat()  When both producer and consumer are done with processing the file, shared memory should be deleted using shmdt()  Semaphores should be deleted by the producer after successful processing of the file using shmctl()

Lab 10: producer.c and consumer.c  NOTE: Both semaphore and shared memory SHOULD use the same key value (to maintain consistency)  The same goes for running consumer.c, except it will be the read part of the program  NOTE: consumer.c should be able to write results to a file named output.txt  Basically, this is like copying to a file, except with shared memory  After copying the file, producer should DELETE THE PREVIOUS FILE to show that it has been transferred to the consumer side (we are CUTTING the file, not copying it)  Test your program this way (suggestion):  Copy your producer.c program to a new folder and consumer.c in another new folder  Then copy a file from producer to the folder with consumer.c in it  This is like piping, except that we do it using semaphores

Lab 10: producer.c and consumer.c  You SHOULD be able to handle errors, like wrong arguments, file opening errors, semaphore errors, etc.  Legal stuff  Include a Certificate of Authorship, along with your producer.c and consumer.c programs  Filename: CS162B_Lab10_ _ _.tar  Deadline: Next Week Midnight  Tuesday for Section A  Thursday for Section B