Systems Programming/ C and UNIX

Size: px
Start display at page:

Download "Systems Programming/ C and UNIX"

Transcription

1 Systems Programming/ C and UNIX Alice E. Fischer November 22, 2013 Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

2 Outline 1 Jobs and Job Control 2 Shared Memory Concepts and Definitions Producer / Consumer Revisited Setting Up the Shared Memory 3 Semaphores Signals in the Producer / Consumer Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

3 Jobs and Job Control Jobs and Job Control A Job is a Process Job Control Suspension Foreground and Background Recovering from a Mess Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

4 Jobs and Job Control A Job is a Process. We use the term job to refer to a process that is controlled by a shell. Once started, each job is either in the foreground, running in the background, or suspended. Starting a job the normal way puts it in the foreground: > server2 To start a job in the background, use an ampersand: > server2 & The shell will start the background job, then return immediately to you so that you can start another job that will run concurrently. The output from the background job will still come to the terminal screen. To suspend the foreground process, type Z The suspended job will stop running, but can be restarted. To resume a job after suspension, type ps to find its job number, n then type fg %n or bg %n If you start a job in the background, your shell will control it. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

5 Jobs and Job Control Job Control: server2 and the three clients To prepare for this experiment, I used a shell to start the server: > server2 I opened a second shell and listed the jobs it was controlling: > jobs The list was empty. Then I used the same shell to start three clients at the same time, all running in the background > clientm localhost & clientj localhost & client & Typing jobs again for this shell, we see: > jobs [1] + Running clientj localhost [2] - Running clientm localhost [3] Running client localhost Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

6 Jobs and Job Control Foreground, Background, and Suspension You can only send keyboard input to a foreground job. You can suspend both foreground and background jobs. To move job [2] into the foreground, use: > fg %2 Control-Z suspends the foreground job and returns control to the shell. After suspending clientm we see: > jobs [1] + Running clientj localhost [2] - Suspended clientm localhost [3] Running client localhost To resume work on job [2] in the background or in the foreground use: > bg %2 or > fg %2 Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

7 Jobs and Job Control Foreground and Background A + in the list of jobs marks the current default job. If a fg or bg command is given without a job number, it affects the default job. A - in the list of jobs marks the prior-current job. You can manage this job using %- Output to stdout from all of the running jobs will come to the shell unless stdout was redirected when the job was started. If the shell is in the foreground, and a background job has produced some output, hit return to get a command prompt. Suppose one of your running background jobs ends with a fatal error and is waiting for you to release it. You must bring it to the foreground, then release it. It will then exit and be gone from the jobs list. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

8 Jobs and Job Control Detached Processes We use a shell to run and control processes. Usually, this is a simple matter; but things can get complex. Suppose your shell is running a job in the background, and it is not suspended. When you close the shell window, that terminates the shell and its foreground process. But it does not terminate a running background process. That process lives on as a detached process. If it is a server, new clients can still attach to it. This can create a mess! To see the detached process, use another shell to type ps a To terminate it gracefully, use kill pid or kill -TERM pid To terminate it immediately, use kill -KILL pid. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

9 Jobs and Job Control Recovering from a Mess Suppose you have made a mess Several jobs are controlled by your shell, Suppose one of them needs to be stopped because it is out of control and not responding to normal signals. You could stop all of the controlled processes by killing the shell. However, this may be a bad idea, because a process running in the background becomes detached when you close its shell. It is like a daemon! If you only want to stop one job, use the kill command. Kill it this way from the same shell window: > kill -KILL %2 Kill it this way from a different shell window: > ps and note the PID in the left-hand column. > kill -KILL using that pid. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

10 Shared Memory Shared Memory Concepts and Definitions Producer and Consumer revisited Setting up a shared memory area Using the shared memory area Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

11 Shared Memory Concepts and Definitions Threads vs. Processes Earlier, we looked at a producer/consumer application that was written as one module and implemented with threads. The producers and consumers in that application were able to share memory that was global in the program that spawned the threads. When we fork off child processes, there is no built-in shared memory. The child process gets a copy of the memory of the parent process, but there is no sharing after that. Similarly, there is no easy sharing mechanism for processes that are started up separately. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

12 Shared Memory Concepts and Definitions Shared Memory for Processes Unix does provide a way for one process to create a shared memory block to which another process can link. The communicating processes can be created by forking or they can be separately compiled and separately started-up. As with shared thread-memory, processes that share blocks of memory must use mutex locks and synchronization primitives to avoid disaster. The example this week is a single producer with a single consumer, which are separately compiled processes and communicate through a shared memory area that was created by the consumer. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

13 Shared Memory Producer / Consumer Revisited Producer / Consumer Revisited producer.c / consumer.c The consumer will be the last one to use or need the shared memory. Therefore, it creates and frees the shared memory block and the semaphores that coordinate it. The shared memory block stores a single variable: a structure that contains a bounded queue, status flags, and the semaphores to regulate access to the queue. Most communication between the producer and the consumer is through the shared memory. In addition, the producer sends one signal to the consumer. The consumer must be started first. The program will run until you stop one of the processes with a CTRL-C. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

14 Shared Memory Producer / Consumer Revisited Producer / Consumer Logic The producer calculates data, stores it in the shared queue if slots are available If not, it waits for more slots to appear. Concurrently, the consumer removes letters from the queue and prints them, as long as there are any to remove. Then it waits for more. Both processes output the letters so that you can see that the queue and the communication both work. If the consumer receives a SIGINT, it sets a flag that tells the producer to stop, then it continues its work. The producer s SIGINT handler sets the same flag. If producer sees the flag set (for either reason), it stops producing more output, sets the producerdone flag, and signals the consumer to ensure that the consumer is awake to read the flags. Then it quits. When the consumer sees the producerdone flag, it cleans out the queue, releases the shared resources, and quits. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

15 Shared Memory A Shared Memory Block has an ID# Setting Up the Shared Memory This part of the project is easy. Each block of shared memory must be given a unique identifier. A block-id can be any integer; it is quite arbitrary. The same block-id code must be defined by every process that shares the memory block. This is most easily handled by putting the codes in a header file that is included by all parts of the application: #define SHMKEY 123 // Unique ID of shared memory. One process must create the shared memory. Here, we create space for an array of char. 0x1FF is the permission mode (9 perm bits). shmid = shmget(shmkey, BUFSIZE*sizeof(char), IPC_CREAT 0x1FF ); Other processes can then link to the existing shared memory: shmid = shmget(shmkey, BUFSIZE*sizeof(char), 0); Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

16 Shared Memory Using the Shared Memory: Producer Setting Up the Shared Memory Any process that uses the shared memory must attach it to a local variable name of the correct type, in this case, memoryt*. memoryt* m; m = shmat(shmid, NULL, 0); When both the shared memory and the controlling semaphores have been set up, our producer enters a loop in which it computes items and enqueues them: char ch = rand() % 26 + A ; enqueue(m, ch); enqueue prints debugging information, waits for the two semaphores that control the shared queue, and puts the data into the queue: m->buffer[m->tail] = ch; // Modify the queue. m->tail = (m->tail + 1) % QSIZE; Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

17 Shared Memory Setting Up the Shared Memory Using the Shared Memory: Consumer The consumer must also map the shared memory into its own address space, then it must initialize all the shared variables: m->consumerpid = getpid(); m->requeststop = m->producerdone = false; m->head = m->tail = 0; m->semid = semid; m->shmid = shmid; Similarly, the consumer executes a production loop that dequeues data until the producer quits: while (!m->producerdone) { printf("consumed: %c\n", dequeue(m)); } dequeue prints debugging information, waits for the two semaphores that control the shared queue, and puts the data into the queue: char ch = m->buffer[m->head]; m->head = (m->head + 1) % QSIZE; Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

18 Semaphores Semaphores Synchronization of Processes Creating a Semaphore How Counting Semaphores Work Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

19 Semaphores Synchronization of Processes Whenever two threads or two processes share a memory area, it must be protected by excluding all other processes while one process reads or writes the common area. Implementing mutual exclusion with threads requires setting up a mutex and a semaphore. These can be set up in the shared memory area before the threads are created, and they will automatically have access. Four functions from the pthread package are used to manage the locks: pthread_mutex_lock, pthread_mutex_unlock, pthread_cond_wait(), and pthread_cond_signal(). Failure to use the locks properly could result in several kinds of failure. For processes, semaphores are used for synchronization; they include the functionality of both locks and condition variables, but they work at a more primitive level. In addition, some sort of signaling capability must be implemented, through shared memory, signaling system calls, or both. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

20 Semaphores How Counting Semaphores Work The WAIT and POST operations are executed atomically. POST increments a semaphore s counter and wakes up a process that is waiting on it. WAIT tests the counter and blocks the process if it is 0. When some other process increments the counter by executing POST, WAIT decrements the counter and execution proceeds. If the semaphore is > 0 when WAIT is called, WAIT immediately decrements the counter and execution proceeds. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

21 Creating a Semaphore Semaphores A Unix semaphore implements a counter that can never go < 0. We use semaphores that count up and down to handle synchronization for the producer / consumer application. We use a true/false semaphore to handle mutual exclusion. Semaphores are implemented in kernel memory, handled by the kernel, and delivered to us through a shared-memory segment its own unique ID code: #define SEMKEY 222 // ID of semaphore memory. In the consumer, we request, or create, 3 semaphores: semid = semget(semkey, 3, IPC_CREAT 0x1FF); The parallel call in the producer attaches to 3 existing semaphores: semid = semget(semkey, 3, 0); Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

22 Semaphores Shared Memory Needs Coordination To use a semaphore, you must initialize it and define WAIT and POST. We initialize the three semaphores. semctl( semid, ITEMS, SETVAL, 0 ); semctl( semid, SLOTS, SETVAL, QSIZE ); semctl( semid, MUTEX, SETVAL, 1); The function semwait() performs the WAIT semantics. sempost() performs the POST semantics. semid[items] counts the number of items in the shared queue. semid[slots] counts the number of available slots in the queue. The sum of the values in ITEMS and SLOTS will = QSIZE. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

23 Semaphores Using WAIT and POST Except for creation and initialization, the producer and consumer use the semaphores in a symmetric manner. The producer will WAIT on semid[slots] before using the shared memory and POST to semid[items] when it finishes. The consumer will WAIT on semid[items] before using the shared memory and POST to semid[slots] when it finishes. In this way, each process will lock and unlock the shared memory, alternately blocking and releasing the other process. The sempost functions are simpler than the semwait functions because they never block. The semwait for the producer is simpler than the semwait for the consumer. Both must check for errors, but if a termination signal comes into the producer, he can just quit. The consumer must empty the queue before quitting. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

24 Semaphores The sembuf Array To use a counting semaphore, you must create an array of sembuf objects. Each object in the array represents some action to be performed on a semaphore. All actions are performed atomically. In this program, we use an array with exactly one entry. Here we set up the sembuf array for WAIT; semnum is the # of the semaphore on which we are waiting: static struct sembuf decrement[1]; decrement[0].sem_num = semnum; decrement[0].sem_op = -1; decrement[0].sem_flg = 0; The sem_op tells the semaphore to subtract from its counter each time semwait is called. The sem_flg is a set of flags that can be used to modify the semaphore s behavior. Use 0 for simple protocols. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

25 Semaphores Calling semop() To execute a semaphore operation (lock/unlock and count + or -) use semop(). This is the code from the producer s semwait int status = semop(semid, decrement, 1); if (status < 0 ) { if (errno!= EINTR) fatalp("unexpected interrupt in semwait."); } The first parameter is the semaphore ID# that was returned from semget. The second parameter is the sembuf array (actions to perform). The third parameter is the number of actions in the sembuf array. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

26 Semaphores Signals in the Producer / Consumer The Shut-Down Sequence This is how the program terminates. The user can signal either process to initiate the shut-down. This causes the requeststop flag to be set in the shared memory. The producer checks requeststop before producing an item. If the flag is on, it sets producerdone to true and wakes up the consumer by sending it a SIGINT. Then it quits. When the consumer sees that producerdone is true, it changes the decrement operation in semwait by setting its flags to IPC_NOWAIT. The semaphore continues to operate and decrement the counter, but it will never again block. Then the consumer continues emptying the queue until nothing is left. Now the shared memory and semaphores are released, and the consumer exits. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

27 Semaphores Signals in the Producer / Consumer Summary It is deep and sophisticated, but simple enough to use. It works! Create or attach to the shared memory. Map the handle for the shared memory into your own variable. Create and initialize the shared semaphores. Define functions with arrays of sembuf objects to implement the semaphore-protocol operations. Call SemWait() before using a shared memory resource. Call SemPost() after using a shared memory resource. Be sure to use the proper semaphore-subscript for WAIT and POST. BE SURE TO CHECK the error return codes from all system calls. Alice E. Fischer () Systems Programming Lecture /27 November 22, / 27

Lecture 18. Log into Linux. Copy two subdirectories in /home/hwang/cs375/lecture18/ $ cp r /home/hwang/cs375/lecture18/*.

Lecture 18. Log into Linux. Copy two subdirectories in /home/hwang/cs375/lecture18/ $ cp r /home/hwang/cs375/lecture18/*. Lecture 18 Log into Linux. Copy two subdirectories in /home/hwang/cs375/lecture18/ $ cp r /home/hwang/cs375/lecture18/*. Both subdirectories have makefiles. The "sysv" subdirectory has an example/exercise

More information

CSPP System V IPC 1. System V IPC. Unix Systems Programming CSPP 51081

CSPP System V IPC 1. System V IPC. Unix Systems Programming CSPP 51081 System V IPC 1 System V IPC System V IPC 2 System V IPC Overview System V IPC 3 System V InterProcess Communication (IPC) Provides three mechanisms for sharing data between processes message queues (similar

More information

Unix Inter-process Communication

Unix Inter-process Communication Unix Inter-process Communication Chris Kauffman CS 499: Spring 2016 GMU Mini-exam 2 back Results overall good (again) Stat Val Mini-exam 2 Count 32 Average 35.84 89.6% Median 36.00 90.0% Standard Deviation

More information

W4118 Operating Systems. Instructor: Junfeng Yang

W4118 Operating Systems. Instructor: Junfeng Yang W4118 Operating Systems Instructor: Junfeng Yang Outline Semaphores Producer-consumer problem Monitors and condition variables 2 Semaphore motivation Problem with lock: mutual exclusion, but no ordering

More information

Interprocess Communication. Originally multiple approaches Today more standard some differences between distributions still exist

Interprocess Communication. Originally multiple approaches Today more standard some differences between distributions still exist Interprocess Communication Originally multiple approaches Today more standard some differences between distributions still exist Pipes Oldest form of IPC provided by all distros Limitations Historically

More information

POSIX / System Programming

POSIX / System Programming POSIX / System Programming ECE 650 Methods and Tools for Software Eng. Guest lecture 2017 10 06 Carlos Moreno cmoreno@uwaterloo.ca E5-4111 2 Outline During today's lecture, we'll look at: Some of POSIX

More information

Using IPC: semaphores Interprocess communication using semaphores. Lecturer: Erick Fredj

Using IPC: semaphores Interprocess communication using semaphores. Lecturer: Erick Fredj Using IPC: semaphores Interprocess communication using semaphores Lecturer: Erick Fredj What is a 'semaphore'? A classical approach for restricting access to shared resources in multi-process environments

More information

COP 4604 UNIX System Programming IPC. Dr. Sam Hsu Computer Science & Engineering Florida Atlantic University

COP 4604 UNIX System Programming IPC. Dr. Sam Hsu Computer Science & Engineering Florida Atlantic University COP 4604 UNIX System Programming IPC Dr. Sam Hsu Computer Science & Engineering Florida Atlantic University Interprocess Communication Interprocess communication (IPC) provides two major functions/services:

More information

Synchroniza+on II COMS W4118

Synchroniza+on II COMS W4118 Synchroniza+on II COMS W4118 References: Opera+ng Systems Concepts (9e), Linux Kernel Development, previous W4118s Copyright no2ce: care has been taken to use only those web images deemed by the instructor

More information

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),

More information

Synchronization. Dr. Yingwu Zhu

Synchronization. Dr. Yingwu Zhu Synchronization Dr. Yingwu Zhu Synchronization Threads cooperate in multithreaded programs To share resources, access shared data structures Threads accessing a memory cache in a Web server To coordinate

More information

UNIX Input/Output Buffering

UNIX Input/Output Buffering UNIX Input/Output Buffering When a C/C++ program begins execution, the operating system environment is responsible for opening three files and providing file pointers to them: stdout standard output stderr

More information

Part II Processes and Threads Process Basics

Part II Processes and Threads Process Basics Part II Processes and Threads Process Basics Fall 2017 Program testing can be used to show the presence of bugs, but never to show their absence 1 Edsger W. Dijkstra From Compilation to Execution A compiler

More information

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012

Pre-lab #2 tutorial. ECE 254 Operating Systems and Systems Programming. May 24, 2012 Pre-lab #2 tutorial ECE 254 Operating Systems and Systems Programming May 24, 2012 Content Concurrency Concurrent Programming Thread vs. Process POSIX Threads Synchronization and Critical Sections Mutexes

More information

CS4961 Parallel Programming. Lecture 12: Advanced Synchronization (Pthreads) 10/4/11. Administrative. Mary Hall October 4, 2011

CS4961 Parallel Programming. Lecture 12: Advanced Synchronization (Pthreads) 10/4/11. Administrative. Mary Hall October 4, 2011 CS4961 Parallel Programming Lecture 12: Advanced Synchronization (Pthreads) Mary Hall October 4, 2011 Administrative Thursday s class Meet in WEB L130 to go over programming assignment Midterm on Thursday

More information

Systems Programming/ C and UNIX

Systems Programming/ C and UNIX Systems Programming/ C and UNIX A. Fischer CSCI 4547 / 6647 November 16, 2017 A. Fischer CSCI 4547 / 6647 Systems Programming Lecture 8... 1/20 November 16, 2017 1 / 20 Outline 1 Signals for Threads Signals

More information

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1 Synchronization and Semaphores Copyright : University of Illinois CS 241 Staff 1 Synchronization Primatives Counting Semaphores Permit a limited number of threads to execute a section of the code Binary

More information

CS 25200: Systems Programming. Lecture 26: Classic Synchronization Problems

CS 25200: Systems Programming. Lecture 26: Classic Synchronization Problems CS 25200: Systems Programming Lecture 26: Classic Synchronization Problems Dr. Jef Turkstra 2018 Dr. Jeffrey A. Turkstra 1 Announcements Lab 5 posted this evening Web server Password protection SSL cgi-bin

More information

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 8: Semaphores, Monitors, & Condition Variables 8.0 Main Points: Definition of semaphores Example of use

More information

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University Semaphores Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Synchronization

More information

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017 CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution

More information

ENGR 3950U / CSCI 3020U UOIT, Fall 2012 Quiz on Process Synchronization SOLUTIONS

ENGR 3950U / CSCI 3020U UOIT, Fall 2012 Quiz on Process Synchronization SOLUTIONS Name: Student Number: SOLUTIONS ENGR 3950U / CSCI 3020U (Operating Systems) Quiz on Process Synchronization November 13, 2012, Duration: 40 Minutes (10 questions and 8 pages, 45 Marks) Instructor: Dr.

More information

Programs. Program: Set of commands stored in a file Stored on disk Starting a program creates a process static Process: Program loaded in RAM dynamic

Programs. Program: Set of commands stored in a file Stored on disk Starting a program creates a process static Process: Program loaded in RAM dynamic Programs Program: Set of commands stored in a file Stored on disk Starting a program creates a process static Process: Program loaded in RAM dynamic Types of Processes 1. User process: Process started

More information

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 The Process Concept 2 The Process Concept Process a program in execution

More information

Process Synchronization. studykorner.org

Process Synchronization. studykorner.org Process Synchronization Semaphore Implementation Must guarantee that no two processes can execute wait () and signal () on the same semaphore at the same time The main disadvantage of the semaphore definition

More information

Solving the Producer Consumer Problem with PThreads

Solving the Producer Consumer Problem with PThreads Solving the Producer Consumer Problem with PThreads Michael Jantz Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads: Producer-Consumer 1 Introduction This lab is an extension of last week's lab.

More information

Parallel Programming Languages COMP360

Parallel Programming Languages COMP360 Parallel Programming Languages COMP360 The way the processor industry is going, is to add more and more cores, but nobody knows how to program those things. I mean, two, yeah; four, not really; eight,

More information

Each terminal window has a process group associated with it this defines the current foreground process group. Keyboard-generated signals are sent to

Each terminal window has a process group associated with it this defines the current foreground process group. Keyboard-generated signals are sent to Each terminal window has a process group associated with it this defines the current foreground process group. Keyboard-generated signals are sent to all processes in the current window s process group.

More information

Synchronization. Semaphores implementation

Synchronization. Semaphores implementation Synchronization Semaphores implementation Possible implementations There are seeral possible implementations (standard and non standard)of a semaphore Semaphores through pipe POSIX semaphores Linux semaphores

More information

CS 345 Operating Systems. Tutorial 2: Treasure Room Simulation Threads, Shared Memory, Synchronization

CS 345 Operating Systems. Tutorial 2: Treasure Room Simulation Threads, Shared Memory, Synchronization CS 345 Operating Systems Tutorial 2: Treasure Room Simulation Threads, Shared Memory, Synchronization Assignment 2 We have a treasure room, Team A and Team B. Treasure room has N coins inside. Each team

More information

Introduction to PThreads and Basic Synchronization

Introduction to PThreads and Basic Synchronization Introduction to PThreads and Basic Synchronization Michael Jantz, Dr. Prasad Kulkarni Dr. Douglas Niehaus EECS 678 Pthreads Introduction Lab 1 Introduction In this lab, we will learn about some basic synchronization

More information

Mid Term from Feb-2005 to Nov 2012 CS604- Operating System

Mid Term from Feb-2005 to Nov 2012 CS604- Operating System Mid Term from Feb-2005 to Nov 2012 CS604- Operating System Latest Solved from Mid term Papers Resource Person Hina 1-The problem with priority scheduling algorithm is. Deadlock Starvation (Page# 84) Aging

More information

Lecture 8: September 30

Lecture 8: September 30 CMPSCI 377 Operating Systems Fall 2013 Lecture 8: September 30 Lecturer: Prashant Shenoy Scribe: Armand Halbert 8.1 Semaphores A semaphore is a more generalized form of a lock that can be used to regulate

More information

Concurrency: a crash course

Concurrency: a crash course Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Concurrency: a crash course Concurrent computing Applications designed as a collection of computational units that may execute

More information

PROCESS SYNCHRONIZATION

PROCESS SYNCHRONIZATION PROCESS SYNCHRONIZATION Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization

More information

Unix Processes. What is a Process?

Unix Processes. What is a Process? Unix Processes Process -- program in execution shell spawns a process for each command and terminates it when the command completes Many processes all multiplexed to a single processor (or a small number

More information

Inter-process communication (IPC)

Inter-process communication (IPC) Inter-process communication (IPC) Operating Systems Kartik Gopalan References Chapter 5 of OSTEP book. Unix man pages Advanced Programming in Unix Environment by Richard Stevens http://www.kohala.com/start/apue.html

More information

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1

Synchronization and Semaphores. Copyright : University of Illinois CS 241 Staff 1 Synchronization and Semaphores Copyright : University of Illinois CS 241 Staff 1 Synchronization Primatives Counting Semaphores Permit a limited number of threads to execute a section of the code Binary

More information

CMSC421: Principles of Operating Systems

CMSC421: Principles of Operating Systems CMSC421: Principles of Operating Systems Nilanjan Banerjee Assistant Professor, University of Maryland Baltimore County nilanb@umbc.edu http://www.csee.umbc.edu/~nilanb/teaching/421/ Principles of Operating

More information

C09: Process Synchronization

C09: Process Synchronization CISC 7310X C09: Process Synchronization Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/29/2018 CUNY Brooklyn College 1 Outline Race condition and critical regions The bounded

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Objectives Introduce Concept of Critical-Section Problem Hardware and Software Solutions of Critical-Section Problem Concept of Atomic Transaction Operating Systems CS

More information

CS 385 Operating Systems Fall 2013 Homework Assignment 2 Inter-Process Communications and Synchronization

CS 385 Operating Systems Fall 2013 Homework Assignment 2 Inter-Process Communications and Synchronization CS 385 Operating Systems Fall 2013 Homework Assignment 2 Inter-Process Communications and Synchronization Due: Tuesday October15 th at 3:00 P.M. via Blackboard. Optional hard copy may be submitted to the

More information

Synchronising Threads

Synchronising Threads Synchronising Threads David Chisnall March 1, 2011 First Rule for Maintainable Concurrent Code No data may be both mutable and aliased Harder Problems Data is shared and mutable Access to it must be protected

More information

Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017

Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Races and Deadlocks! (or The Dangers of Threading) CS449 Fall 2017 Data Race Shared Data: 465 1 8 5 6 209? tail A[] thread switch Enqueue(): A[tail] = 20; tail++; A[tail] = 9; tail++; Thread 0 Thread

More information

Most of the work is done in the context of the process rather than handled separately by the kernel

Most of the work is done in the context of the process rather than handled separately by the kernel Process Control Process Abstraction for a running program Manages program s use of memory, cpu time, and i/o resources Most of the work is done in the context of the process rather than handled separately

More information

CS370 Operating Systems Midterm Review

CS370 Operating Systems Midterm Review CS370 Operating Systems Midterm Review Yashwant K Malaiya Fall 2015 Slides based on Text by Silberschatz, Galvin, Gagne 1 1 What is an Operating System? An OS is a program that acts an intermediary between

More information

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor.

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor. Synchronization 1 Concurrency On multiprocessors, several threads can execute simultaneously, one on each processor. On uniprocessors, only one thread executes at a time. However, because of preemption

More information

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018 SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T 2. 3. 8 A N D 2. 3. 1 0 S P R I N G 2018 INTER-PROCESS COMMUNICATION 1. How a process pass information to another process

More information

Interprocess Communication

Interprocess Communication Interprocess Communication Reading: Silberschatz chapter 4 Additional Reading: Stallings chapter 6 EEL 358 1 Outline Introduction Shared memory systems POSIX shared memory Message passing systems Direct

More information

Interprocess Communication and Synchronization

Interprocess Communication and Synchronization Chapter 2 (Second Part) Interprocess Communication and Synchronization Slide Credits: Jonathan Walpole Andrew Tanenbaum 1 Outline Race Conditions Mutual Exclusion and Critical Regions Mutex s Test-And-Set

More information

Process Synchronization

Process Synchronization Process Synchronization Part III, Modified by M.Rebaudengo - 2013 Silberschatz, Galvin and Gagne 2009 POSIX Synchronization POSIX.1b standard was adopted in 1993 Pthreads API is OS-independent It provides:

More information

Process Management forks, bombs, zombies, and daemons! Lecture 5, Hands-On Unix System Administration DeCal

Process Management forks, bombs, zombies, and daemons! Lecture 5, Hands-On Unix System Administration DeCal Process Management forks, bombs, zombies, and daemons! Lecture 5, Hands-On Unix System Administration DeCal 2012-10-01 what is a process? an abstraction! you can think of it as a program in the midst of

More information

INTER-PROCESS COMMUNICATION. UNIX Programming 2015 Fall by Euiseong Seo

INTER-PROCESS COMMUNICATION. UNIX Programming 2015 Fall by Euiseong Seo INTER-PROCESS COMMUNICATION UNIX Programming 2015 Fall by Euiseong Seo Named Pipes Anonymous pipes can be used only between related processes Processes not from the same ancestor sometimes need to communicate

More information

CS 385 Operating Systems Spring 2013 Homework Assignment 2 Third Draft Inter-Process Communications and Synchronization

CS 385 Operating Systems Spring 2013 Homework Assignment 2 Third Draft Inter-Process Communications and Synchronization CS 385 Operating Systems Spring 2013 Homework Assignment 2 Third Draft Inter-Process Communications and Synchronization Due: Thursday March 14 th at 3:00 P.M. via Blackboard. Optional hard copy may be

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 11: Semaphores I" Brian Logan School of Computer Science bsl@cs.nott.ac.uk Outline of this lecture" problems with Peterson s algorithm semaphores implementing semaphores

More information

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files ... and systems programming C basic syntax functions arrays structs

More information

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs.

CSC209: Software tools. Unix files and directories permissions utilities/commands Shell programming quoting wild cards files. Compiler vs. CSC209 Review CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files... and systems programming C basic syntax functions arrays structs

More information

CS 105, Spring 2007 Ring Buffer

CS 105, Spring 2007 Ring Buffer CS 105, Spring 2007 Ring Buffer April 11, 2007 1 Introduction A ring buffer, also called a circular buffer, is a common method of sharing information between a producer and a consumer. In class, we have

More information

UNIT III- INTER PROCESS COMMUNICATIONS Part A

UNIT III- INTER PROCESS COMMUNICATIONS Part A UNIT III- INTER PROCESS COMMUNICATIONS Part A 1 What are the different communications supported by UNIX? Inter process communication and network communication 2 What do you mean by Inter process communication?

More information

CS 470 Spring Mike Lam, Professor. Semaphores and Conditions

CS 470 Spring Mike Lam, Professor. Semaphores and Conditions CS 470 Spring 2018 Mike Lam, Professor Semaphores and Conditions Synchronization mechanisms Busy-waiting (wasteful!) Atomic instructions (e.g., LOCK prefix in x86) Pthreads Mutex: simple mutual exclusion

More information

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T Operating Systems Operating Systems Summer 2017 Sina Meraji U of T More Special Instructions Swap (or Exchange) instruction Operates on two words atomically Can also be used to solve critical section problem

More information

CS604 - Operating System Solved Subjective Midterm Papers For Midterm Exam Preparation

CS604 - Operating System Solved Subjective Midterm Papers For Midterm Exam Preparation CS604 - Operating System Solved Subjective Midterm Papers For Midterm Exam Preparation The given code is as following; boolean flag[2]; int turn; do { flag[i]=true; turn=j; while(flag[j] && turn==j); critical

More information

Operating systems. Lecture 3 Interprocess communication. Narcis ILISEI, 2018

Operating systems. Lecture 3 Interprocess communication. Narcis ILISEI, 2018 Operating systems Lecture 3 Interprocess communication Narcis ILISEI, 2018 Goals for today Race Condition Critical Region Mutex / Monitor Semaphore Inter-process communication (IPC) A mechanism that allows

More information

THE PROCESS ABSTRACTION. CS124 Operating Systems Winter , Lecture 7

THE PROCESS ABSTRACTION. CS124 Operating Systems Winter , Lecture 7 THE PROCESS ABSTRACTION CS124 Operating Systems Winter 2015-2016, Lecture 7 2 The Process Abstraction Most modern OSes include the notion of a process Term is short for a sequential process Frequently

More information

CSCI 4061: Inter-Process Communication

CSCI 4061: Inter-Process Communication 1 CSCI 4061: Inter-Process Communication Chris Kauffman Last Updated: Tue Nov 7 12:34:27 CST 2017 2 Logistics Reading Stevens/Rago Ch 15.6-12 Robbins and Robbins Ch 15.1-4 Goals Protocols for Cooperation

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008.

CSC Operating Systems Spring Lecture - XII Midterm Review. Tevfik Ko!ar. Louisiana State University. March 4 th, 2008. CSC 4103 - Operating Systems Spring 2008 Lecture - XII Midterm Review Tevfik Ko!ar Louisiana State University March 4 th, 2008 1 I/O Structure After I/O starts, control returns to user program only upon

More information

UNIX IPC. Unix Semaphore Unix Message queue

UNIX IPC. Unix Semaphore Unix Message queue UNIX IPC Unix Semaphore Unix Message queue 1 UNIX SEMAPHORE: Unix semaphore is not a single variable but an array of non-negative integer variables. Number of non-negative values: 1 to some system defined

More information

Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - III Processes. Louisiana State University. Processes. September 1 st, 2009

Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - III Processes. Louisiana State University. Processes. September 1 st, 2009 CSC 4103 - Operating Systems Fall 2009 Lecture - III Processes Tevfik Ko!ar Louisiana State University September 1 st, 2009 1 Roadmap Processes Basic Concepts Process Creation Process Termination Context

More information

CS Lecture 3! Threads! George Mason University! Spring 2010!

CS Lecture 3! Threads! George Mason University! Spring 2010! CS 571 - Lecture 3! Threads! George Mason University! Spring 2010! Threads! Overview! Multithreading! Example Applications! User-level Threads! Kernel-level Threads! Hybrid Implementation! Observing Threads!

More information

! The Process Control Block (PCB) " is included in the context,

! The Process Control Block (PCB)  is included in the context, CSE 421/521 - Operating Systems Fall 2012 Lecture - III Processes Tevfik Koşar Roadmap Processes Basic Concepts Process Creation Process Termination Context Switching Process Queues Process Scheduling

More information

(MCQZ-CS604 Operating Systems)

(MCQZ-CS604 Operating Systems) command to resume the execution of a suspended job in the foreground fg (Page 68) bg jobs kill commands in Linux is used to copy file is cp (Page 30) mv mkdir The process id returned to the child process

More information

CSC209 Review. Yeah! We made it!

CSC209 Review. Yeah! We made it! CSC209 Review Yeah! We made it! 1 CSC209: Software tools Unix files and directories permissions utilities/commands Shell programming quoting wild cards files 2 ... and C programming... C basic syntax functions

More information

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Operating Systems Lecture 4 - Concurrency and Synchronization Adrien Krähenbühl Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Mutual exclusion Hardware solutions Semaphores IPC: Message passing

More information

1 Process Coordination

1 Process Coordination COMP 730 (242) Class Notes Section 5: Process Coordination 1 Process Coordination Process coordination consists of synchronization and mutual exclusion, which were discussed earlier. We will now study

More information

CS 385 Operating Systems Fall 2011 Homework Assignment 5 Process Synchronization and Communications

CS 385 Operating Systems Fall 2011 Homework Assignment 5 Process Synchronization and Communications CS 385 Operating Systems Fall 2011 Homework Assignment 5 Process Synchronization and Communications Due: Friday December 2 at 8:00 P.M. via Blackboard Overall Assignment Man Pages For this assignment,

More information

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack What is it? Recap: Thread Independent flow of control What does it need (thread private)? Stack What for? Lightweight programming construct for concurrent activities How to implement? Kernel thread vs.

More information

Concurrency. Chapter 5

Concurrency. Chapter 5 Concurrency 1 Chapter 5 2 Concurrency Is a fundamental concept in operating system design Processes execute interleaved in time on a single processor Creates the illusion of simultaneous execution Benefits

More information

Operating systems and concurrency (B08)

Operating systems and concurrency (B08) Operating systems and concurrency (B08) David Kendall Northumbria University David Kendall (Northumbria University) Operating systems and concurrency (B08) 1 / 20 Introduction Semaphores provide an unstructured

More information

More Types of Synchronization 11/29/16

More Types of Synchronization 11/29/16 More Types of Synchronization 11/29/16 Today s Agenda Classic thread patterns Other parallel programming patterns More synchronization primitives: RW locks Condition variables Semaphores Message passing

More information

CSCI0330 Intro Computer Systems Doeppner. Project Shell 2. Due: November 8, 2017 at 11:59pm. 1 Introduction 2

CSCI0330 Intro Computer Systems Doeppner. Project Shell 2. Due: November 8, 2017 at 11:59pm. 1 Introduction 2 CSCI0330 Intro Computer Systems Doeppner Project Shell 2 Due: November 8, 2017 at 11:59pm 1 Introduction 2 2 Assignment 2 2.1 Stencil 2 2.2 Jobs vs. Processes 2 2.3 Foreground vs. Background 3 2.4 Specification

More information

CS 4410, Fall 2017 Project 1: My First Shell Assigned: August 27, 2017 Due: Monday, September 11:59PM

CS 4410, Fall 2017 Project 1: My First Shell Assigned: August 27, 2017 Due: Monday, September 11:59PM CS 4410, Fall 2017 Project 1: My First Shell Assigned: August 27, 2017 Due: Monday, September 11th @ 11:59PM Introduction The purpose of this assignment is to become more familiar with the concepts of

More information

Chapter 6 Concurrency: Deadlock and Starvation

Chapter 6 Concurrency: Deadlock and Starvation Operating Systems: Internals and Design Principles Chapter 6 Concurrency: Deadlock and Starvation Seventh Edition By William Stallings Operating Systems: Internals and Design Principles When two trains

More information

Multitasking. Programmer s model of multitasking. fork() spawns new process. exit() terminates own process

Multitasking. Programmer s model of multitasking. fork() spawns new process. exit() terminates own process Signals Prof. Jin-Soo Kim( jinsookim@skku.edu) TA JinHong Kim( jinhong.kim@csl.skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Multitasking Programmer s model of multitasking

More information

Last Class: CPU Scheduling! Adjusting Priorities in MLFQ!

Last Class: CPU Scheduling! Adjusting Priorities in MLFQ! Last Class: CPU Scheduling! Scheduling Algorithms: FCFS Round Robin SJF Multilevel Feedback Queues Lottery Scheduling Review questions: How does each work? Advantages? Disadvantages? Lecture 7, page 1

More information

ENGR 3950U / CSCI 3020U Midterm Exam SOLUTIONS, Fall 2012 SOLUTIONS

ENGR 3950U / CSCI 3020U Midterm Exam SOLUTIONS, Fall 2012 SOLUTIONS SOLUTIONS ENGR 3950U / CSCI 3020U (Operating Systems) Midterm Exam October 23, 2012, Duration: 80 Minutes (10 pages, 12 questions, 100 Marks) Instructor: Dr. Kamran Sartipi Question 1 (Computer Systgem)

More information

More Shared Memory Programming

More Shared Memory Programming More Shared Memory Programming Shared data structures We want to make data structures that can be shared by threads. For example, our program to copy a file from one disk to another used a shared FIFO

More information

Chapter 6: Synchronization. Operating System Concepts 8 th Edition,

Chapter 6: Synchronization. Operating System Concepts 8 th Edition, Chapter 6: Synchronization, Silberschatz, Galvin and Gagne 2009 Outline Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization

More information

Signals. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Signals. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University Signals Jin-Soo Kim (jinsookim@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Multitasking (1) Programmer s model of multitasking fork() spawns new process Called once,

More information

Advanced Unix Concepts. Satyajit Rai

Advanced Unix Concepts. Satyajit Rai Advanced Unix Concepts Advanced Unix Concepts Satyajit Rai March 17, 2003 March 22, 2003 KReSIT, IIT Bombay 1 Contents Contents Advanced Unix Concepts.......... 1 Contents.................. 2 Process Creation..............

More information

Subject: Operating System (BTCOC403) Class: S.Y.B.Tech. (Computer Engineering)

Subject: Operating System (BTCOC403) Class: S.Y.B.Tech. (Computer Engineering) A. Multiple Choice Questions (60 questions) Subject: Operating System (BTCOC403) Class: S.Y.B.Tech. (Computer Engineering) Unit-I 1. What is operating system? a) collection of programs that manages hardware

More information

Operating Systems. VI. Threads. Eurecom. Processes and Threads Multithreading Models

Operating Systems. VI. Threads. Eurecom. Processes and Threads Multithreading Models Operating Systems VI. Threads Ludovic Apvrille ludovic.apvrille@telecom-paristech.fr Eurecom, office 470 http://soc.eurecom.fr/os/ @OS Eurecom Outline 2/36 Fall 2017 Institut Mines-Telecom Operating Systems

More information

High-level Synchronization

High-level Synchronization Recap of Last Class High-level Synchronization CS 256/456 Dept. of Computer Science, University of Rochester Concurrent access to shared data may result in data inconsistency race condition. The Critical-Section

More information

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor.

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor. Synchronization 1 Concurrency On multiprocessors, several threads can execute simultaneously, one on each processor. On uniprocessors, only one thread executes at a time. However, because of preemption

More information

Signals: Management and Implementation. Sanjiv K. Bhatia Univ. of Missouri St. Louis

Signals: Management and Implementation. Sanjiv K. Bhatia Univ. of Missouri St. Louis Signals: Management and Implementation Sanjiv K. Bhatia Univ. of Missouri St. Louis sanjiv@aryabhat.umsl.edu http://www.cs.umsl.edu/~sanjiv Signals Mechanism to notify processes of asynchronous events

More information

Process Synchronization(2)

Process Synchronization(2) CSE 3221.3 Operating System Fundamentals No.6 Process Synchronization(2) Prof. Hui Jiang Dept of Computer Science and Engineering York University Semaphores Problems with the software solutions. Not easy

More information

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; }

Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; } Semaphore Semaphore S integer variable Two standard operations modify S: wait() and signal() Originally called P() and V() Can only be accessed via two indivisible (atomic) operations wait (S) { while

More information

Synchronization Primitives

Synchronization Primitives Synchronization Primitives Locks Synchronization Mechanisms Very primitive constructs with minimal semantics Semaphores A generalization of locks Easy to understand, hard to program with Condition Variables

More information

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions Chapter 2 Processes and Threads [ ] 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling 85 Interprocess Communication Race Conditions Two processes want to access shared memory at

More information

Processes. OS Structure. OS Structure. Modes of Execution. Typical Functions of an OS Kernel. Non-Kernel OS. COMP755 Advanced Operating Systems

Processes. OS Structure. OS Structure. Modes of Execution. Typical Functions of an OS Kernel. Non-Kernel OS. COMP755 Advanced Operating Systems OS Structure Processes COMP755 Advanced Operating Systems An OS has many parts. The Kernel is the core of the OS. It controls the execution of the system. Many OS features run outside of the kernel, such

More information