Processes, Execution and State. Process Operations: fork. Variations on Process Creation. Windows Process Creation.

Similar documents
What is a Process? Processes, Execution and State. Program vs Process Address Space. What is state? Address Space: Data Segments

CS 111. Operating Systems Peter Reiher

CS 111. Operating Systems Peter Reiher

Operating System Control Structures

Introduction to OS Processes in Unix, Linux, and Windows MOS 2.1 Mahmoud El-Gayyar

PROCESS CONTROL BLOCK TWO-STATE MODEL (CONT D)

Processes. Dr. Yingwu Zhu

Major Requirements of an OS

Process Description and Control. Chapter 3

Process Description and Control

Process Description and Control. Major Requirements of an Operating System

Major Requirements of an Operating System Process Description and Control

Announcement. Exercise #2 will be out today. Due date is next Monday

Processes and Non-Preemptive Scheduling. Otto J. Anshus

Processes. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

The Process Abstraction. CMPU 334 Operating Systems Jason Waterman

TCSS 422: OPERATING SYSTEMS

Process Description and Control. Chapter 3

Process Description and Control

CS 31: Intro to Systems Processes. Kevin Webb Swarthmore College March 31, 2016

Process Concepts. CSC400 - Operating Systems. 3. Process Concepts. J. Sumey

Processes. Process Management Chapter 3. When does a process gets created? When does a process gets terminated?

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

518 Lecture Notes Week 3

CPSC 341 OS & Networks. Processes. Dr. Yingwu Zhu

IT 540 Operating Systems ECE519 Advanced Operating Systems

Exceptions and Processes

Process Description and Control. Chapter 3

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

Operating Systems. Lecture 3- Process Description and Control. Masood Niazi Torshiz

Operating Systems. Computer Science & Information Technology (CS) Rank under AIR 100

Today s class. Finish review of C Process description and control. Informationsteknologi. Tuesday, September 18, 2007

Processes and Exceptions

Processes. Sanzheng Qiao. December, Department of Computing and Software

3.1 Introduction. Computers perform operations concurrently

PROCESS STATES AND TRANSITIONS:

Mon Sep 17, 2007 Lecture 3: Process Management

Lecture 4: Memory Management & The Programming Interface

W4118 Operating Systems. Junfeng Yang

Computer Systems II. First Two Major Computer System Evolution Steps

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

Process Time. Steven M. Bellovin January 25,

1.Define signal? NOV DEC 2011 MAY JUNE 2011

Lecture 4: Process Management

Processes. Operating System CS 217. Supports virtual machines. Provides services: User Process. User Process. OS Kernel. Hardware

Processes, PCB, Context Switch

Design Overview of the FreeBSD Kernel CIS 657

* What are the different states for a task in an OS?

Protection and System Calls. Otto J. Anshus

Operating System. Chapter 3. Process. Lynn Choi School of Electrical Engineering

CS 104 Computer Organization and Design

Process Description and Control

Processes. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University

OS lpr. www. nfsd gcc emacs ls 1/27/09. Process Management. CS 537 Lecture 3: Processes. Example OS in operation. Why Processes? Simplicity + Speed

CSE 410: Computer Systems Spring Processes. John Zahorjan Allen Center 534

CSC369 Lecture 2. Larry Zhang

Design Overview of the FreeBSD Kernel. Organization of the Kernel. What Code is Machine Independent?

Process management. What s in a process? What is a process? The OS s process namespace. A process s address space (idealized)

CSE 451: Operating Systems Winter Module 4 Processes. Mark Zbikowski Allen Center 476

OS Structure, Processes & Process Management. Don Porter Portions courtesy Emmett Witchel

Princeton University Computer Science 217: Introduction to Programming Systems Exceptions and Processes

CSC369 Lecture 2. Larry Zhang, September 21, 2015

Processes and Threads. Processes and Threads. Processes (2) Processes (1)

Processes. CS439: Principles of Computer Systems January 30, 2019

Sistemi in Tempo Reale

What is a Process? Processes and Process Management Details for running a program

Lecture Topics. Announcements. Today: Threads (Stallings, chapter , 4.6) Next: Concurrency (Stallings, chapter , 5.

Hardware, Modularity, and Virtualization CS 111

Chap 4, 5: Process. Dongkun Shin, SKKU

VEOS high level design. Revision 2.1 NEC

Lecture 4: Mechanism of process execution. Mythili Vutukuru IIT Bombay

Process. Discussion session 3 1/30/2016

CS 326: Operating Systems. Process Execution. Lecture 5

PROCESS CONCEPTS. Process Concept Relationship to a Program What is a Process? Process Lifecycle Process Management Inter-Process Communication 2.

Reading Assignment 4. n Chapter 4 Threads, due 2/7. 1/31/13 CSE325 - Processes 1

3. Process Management in xv6

www nfsd emacs lpr Process Management CS 537 Lecture 4: Processes Example OS in operation Why Processes? Simplicity + Speed

Getting to know you. Anatomy of a Process. Processes. Of Programs and Processes

Process! Process Creation / Termination! Process Transitions in" the Two-State Process Model! A Two-State Process Model!

CSCE 313 Introduction to Computer Systems. Instructor: Dezhen Song

Processes. Overview. Processes. Process Creation. Process Creation fork() Processes. CPU scheduling. Pål Halvorsen 21/9-2005

Operating System Structure

Processes. CS439: Principles of Computer Systems January 24, 2018

Processes. Process Scheduling, Process Synchronization, and Deadlock will be discussed further in Chapters 5, 6, and 7, respectively.

Dr. Rafiq Zakaria Campus. Maulana Azad College of Arts, Science & Commerce, Aurangabad. Department of Computer Science. Academic Year

CS 537 Lecture 2 - Processes

CSCE 313: Intro to Computer Systems

Processes. CS 475, Spring 2018 Concurrent & Distributed Systems

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 20

Process Scheduling Queues

OS 1 st Exam Name Solution St # (Q1) (19 points) True/False. Circle the appropriate choice (there are no trick questions).

CS 33. Architecture and the OS. CS33 Intro to Computer Systems XIX 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

CS 33. Architecture and the OS. CS33 Intro to Computer Systems XIX 1 Copyright 2018 Thomas W. Doeppner. All rights reserved.

THE PROCESS ABSTRACTION. CS124 Operating Systems Winter , Lecture 7

Processes and Threads

Computer Systems Assignment 2: Fork and Threads Package

CS510 Operating System Foundations. Jonathan Walpole

CSC 539: Operating Systems Structure and Design. Spring 2006

Windows architecture. user. mode. Env. subsystems. Executive. Device drivers Kernel. kernel. mode HAL. Hardware. Process B. Process C.

ECE 550D Fundamentals of Computer Systems and Engineering. Fall 2017

Transcription:

Processes, Execution, and State 3C. Process Operations 3D. Implementing Processes 3E. Asynchronous Exceptions and Events 3U. User-Mode Programs and Exceptions 3F. Execution State Model Process Operations: fork parent and child are identical: data and stack segments are copied all the same files are open code sample: intrc= fork(); if (rc< 0) { fprintf(stderr, Fork failed\n ); } else if (rc== 0) { fprintf(stderr, Child\n ); } else fprintf(stderr, Fork succeeded, child pid = %d\n, rc); 1 2 Variations on Process Creation tabula rasa a blank slate a new process with minimal resources a few resources may be passed from parent most resources opened, from scratch, by child run fork + exec create new process to run a specified command a cloning fork is a more expensive operation much data and resources to be copied convenient for setting up pipelines allows inheritance of exclusive use devices Windows Process Creation The CreateProcess() system call A very flexible way to create a new process Numerous parameters to shape the child name of program to run security attributes (new or inherited) open file handles to pass/inherit environment variables initial working directory 3 4 Process Forking The way Unix/Linux creates processes child is a clone of the parent the classical Computer Science fork operation Occasionally a clone is what you wanted likely for some kinds of parallel programming Program in child process can adjust resources change input/output file descriptors change working directory change environment variables choose which program to run What Happens After a Fork? There are now two processes with different process ID numbers but otherwise nearly identical How do I profitably use that? two processes w/same code & program counter figure out which is which parent process goes one way child process goes another perhaps adjust process resources perhaps load a new program into the process this code takes the place of (CreateProcess) parameters 5 6 1

Process Operations: exec load new program, pass parameters address space is completely recreated open files remain open, disabled signals disabled available in many polymorphisms code sample: char *myargs[3]; myargs[0] = wc ; myargs[1] = myfile ; myargs[2] = NULL; int rc = execvp(myargs[0], myargs); Process Operations: wait await termination of a child process collect exit status code sample: int rc = waitpid(pid, &status, 0); if (rc== 0) { fprintf(stderr, process %d exited rc=%d\n, pid, status); } 7 8 How Processes Terminate Perhaps voluntarily by calling the exit(2)system call Perhaps involuntarily as a result of an unhandled signal/exception a few signals (e.g. SIGKILL) cannot be caught Perhaps at the hand of another a parent sends a termination signal (e.g. TERM) a system management process (e.g. INT, HUP) The State of a Process Registers Program Counter, Processor Status Word Stack Pointer, general registers Address space size and location of text, data, stack segments size and location of supervisor mode stack System Resources and Parameters open files, current working directory,... owning user ID, parent PID, scheduling priority,... 9 10 Representing a Process all (not just OS) objects have descriptors the identity of the object the current state of the object references to other associated objects Process state is in multiple places parameters and object references in a descriptor app execution state is on the stack, in registers each Linux process has a supervisor-mode stack to retain the state of in-progress system calls to save the state of an interrupt preempted process Resident and non-resident State Resident Process Table Non-resident Process State PID: 1 STS: in mem PID: 2 STS: on disk PID: 3 STS: swapout in memory on disk 11 12 2

(resident process descriptor) state that could be needed at any time information needed to schedule process run-state, priority, statistics data needed to signal or awaken process identification information process ID, user ID, group ID, parent ID communication and synchronization resources semaphores, pending signals, mail-boxes pointer to non-resident state 13 (non-resident process state) information needed only when process runs can swap out to free memory for other processes execution state supervisor mode stack including: saved register values, PC, PS pointers to resources used when running current working directory, open file descriptors pointers to text, data and stack segments used to reconstruct the address space 14 Creating a new process allocate/initialize resident process description allocate/initialize non-resident description duplicate parent resource references (e.g. fds) create a virtual address space allocate memory for code, data and stack load/copy program code and data copy/initialize a stack segment set up initial registers (PC, PS, SP) return from supervisor mode into new process Forking and the Data Segments Forked child shares parent s code segment a single read only segment, referenced by both Stack and Data segments are private each process has its own read/write copy child s is initialized as a copy of parent s copies diverge w/subsequent updates Common optimization: Copy-on-Write start with a single shared read/only segment make a copy only if parent (or child) changes it 15 16 Loading (exec) a Program Program to Process Transition We have a load module The output of linkage editor All external references have been resolved All modules combined into a few segments Includes multiple segments (code, data, etc.) A computer cannot execute a load module Computers execute instructions in memory An entirely new address space must be created Memory must be allocated for each segment Code must be copied from load module to memory ELF header target ISA # load sections # info sections Process section 1 header type: code load adr: 0xxx length: ### compiled code 0x00000000 shared code shared lib3 section 2 header type: data load adr: 0xxx length: ### initialized data values private data section 3 header type: sym length: ### symbol table 0x0100000 shared lib1 Program 0x0110000 shared lib2 private stack 0x0120000 0xFFFFFFFF 17 18 3

How to Terminate a Process? Reclaim any resources it may be holding memory locks access to hardware devices Inform any other process that needs to know those waiting for interprocess communications parent (and maybe child) processes Remove process descriptor from process table Asynchronous Events some things are worth waiting for when I read(), I want to wait for the data sometimes waiting doesn t make sense I want to do something else while waiting I have multiple operations outstanding some events demand very prompt attention we need event completion call-backs this is a common programming paradigm computers support interrupts (similar to traps) commonly associated with I/O devices and timers 19 20 Asynchronous Exceptions some errors are routine end of file, arithmetic overflow, conversion error we should check for these after each operation some errors occur unpredictably segmentation fault (e.g. dereferencing NULL) user abort (^C), hang-up, power-failure these must raise asynchronous exceptions some languages support try/catch operations computers support traps operating systems also use these for system calls System Call Trap Gates Application Program 1 st level trap handler system call dispatch table instr ; instr ; instr ; trap ; instr ; instr ; PS/PC PS/PC PS/PC PS/PC TRAP vector table 2 nd level handler (system service implmementation) user mode supervisor mode return to user mode 21 22 (Trap Handling) hardware trap handling trap cause as index into trap vector table for PC/PS load new processor status word, switch to supvmode push PC/PS of program that cuased trap onto stack load PC (w/addrof 1st level handler) software trap handling 1 st level handler pushes all other registers 1 st level handler gathers info, selects 2 nd level handler 2 nd level handler actually deals with the problem handle the event, kill the process, return... Review (User vs. Supervisor mode) the OS executes in supervisor mode able to perform I/O operations able to execute privileged instructions e.g. enable, disable and return from interrupts able update memory management registers to create and modify process address spaces access data structures within the OS application programs execute in user mode they can only execute normal instructions they are restricted to the process's address space 23 24 4

Direct Execution Most operations have no security implications arithmetic, logic, local flow control & data movement Most user-mode programs execute directly CPU fetches, pipelines, and executes each instruction this is very fast, and involves zero overhead A few operations do have security implications h/w refuses to perform these in user-mode these must be performed by the operating system program must request service from the kernel Using Traps for System Calls reserve one illegal instruction for system calls most computers specifically define such instructions define system call linkage conventions call: r0 = system call number, r1 points to arguments return: r0 = return code, cc indicates success/failure prepare arguments for the desired system call execute the designated system call instruction OS recognizes & performs requested operation returns to instruction after the system call 25 26 Stacking and unstacking a System Call (Returning to User-Mode) User-mode Stack stack frames from application computation resumed computation direction of growth Supervisor-mode Stack user mode PC & PS saved user mode registers parameters to system call handler return PC system call handler stack frame return is opposite of interrupt/trap entry 2nd level handler returns to 1st level handler 1st level handler restores all registers from stack use privileged return instruction to restore PC/PS resume user-mode execution at next instruction saved registers can be changed before return change stacked user r0 to reflect return code change stacked user PS to reflect success/failure 27 28 Limited Direct Execution CPU directly executes all application code Punctuated by occasional traps (for system calls) With occasional timer interrupts (for time sharing) Maximizing direct execution is always the goal For Linux user mode processes For OS emulation (e.g., Windows on Linux) For virtual machines Enter the OS as seldom as possible Get back to the application as quickly as possible User-Mode Signal Handling OS defines numerous types of signals exceptions, operator actions, communication processes can control their handling ignore this signal (pretend it never happened) designate a handler for this signal default action (typically kill or coredump process) analogous to hardware traps/interrupts but implemented by the operating system delivered to user mode processes 29 30 5

Signals and Signal Handling when an asynchronous exception occurs the system invokes a specified exception handler invocation looks like a procedure call save state of interrupted computation exception handler can do what ever is necessary handler can return, resume interrupted computation more complex than a procedure call and return must also save/restore condition codes & volatile regs may abort rather than return Signals: sample code int fault_expected, fault_happened; void handler( int sig) { if (!fault_expected) exit(-1); /* if not expected, die */ else fault_happened = 1; /* if expected, note it happened */ } signal(sighup, SIGIGNORE); /* ignore hang-up signals */ signal(sigsegv, &handler); /* handle segmentation faults */... fault_happened = 0; fault_expected = 1;... /* code that might cause a segmentation fault */ fault_expected = 0; 31 32 Stacking a signal delivery execution states with swapping signal handler sees a completely standard appearing stack frame. p1: parameters p0: return address p1: saved registers p1: local variables p1: computation PC/PS (at time of exception) handler: parameters addr of signal unstacker handler: saved registers handler: local variables stack (at time of exception) stack frame (pushed by signal) blocked swap out exit request swapped out running allocate allocate swap wait swap in create ready 33 34 un-dispatching a running process somehow we enter the operating system e.g. via a yield system call or a clock interrupt state of the process has already been preserved user mode PC, PS and registers are already saved on stack supervisor mode registers are also saved on (the supervisor mode) stack descriptions of address space. and pointers to code, data and stack segments, and all other resources are already stored in the process descriptor yield CPU call scheduler to select next process (re-)dispatching a process decision to switch is made in supv mode after state of current process has been saved the scheduler has been called to yield the CPU select the next process to be run get pointer to its process descriptor(s) locate and restore its saved state restore code, data, stack segments restore saved registers, PS, and finally the PC and we are now executing in a new process 35 36 6

Blocking and Unblocking Processes Process needs an unavailable resource data that has not yet been read in from disk a message that has not yet been sent a lock that has not yet been released Must be blocked until resource is available change process state to blocked Un-block when resource becomes available change process state to ready Blocking and unblocking processes blocked/unblocked are merely notes to scheduler blocked processes are not eligible to be dispatched anyone can set them, anyone can change them this usually happens in a resource manager when process needs an unavailable resource change process's scheduling state to "blocked" call the scheduler and yield the CPU when the required resource becomes available change process's scheduling state to "ready" notify scheduler that a change has occurred 37 38 Primary and Secondary Storage primary = main (executable) memory primary storage is expensive and very limited only processes in primary storage can be run secondary = non-executable (e.g. Disk) blocked processes can be moved to secondary storage swap out code, data, stack and non-resident context make room in primary for other "ready" processes returning to primary memory process is copied back when it becomes unblocked Why we swap Make the best use of limited memory a process can only execute if it is in memory max # of processes limited by memory size if it isn't READY, it doesn't need to be in memory Improve CPU utilization when there are no READY processes, CPU is idle idle CPU time is wasted, reduced throughput we need READY processes in memory Swapping takes time and consumes I/O so we want to do it as little as possible 39 40 Swapping Out Process state is in main memory code and data segments non-resident process descriptor Copy them out to secondary storage if we are lucky, some may still be there Update resident process descriptor process is no longer in memory pointer to location on 2ndary storage device Freed memory available for other processes Swapping Back In Re-Allocate memory to contain process code and data segments, non-resident process descriptor Read that data back from secondary storage Change process state back to Ready What about the state of the computations saved registers are on the stack user-mode stack is in the saved data segments supervisor-mode stack is in non-resident descriptor This involves a lot of time and I/O 41 42 7

Forking and Copy on Write Supplementary Slides If the parent had a big data area, setting up a separate copy for the child is expensive And fork was supposed to be cheap If neither parent nor child write the parent s data area, though, no copy necessary So set it up as copy-on-write If one of them writes it, then make a copy and let the process write the copy The other process keeps the original 44 8