Cse v Operating Systems [10cs53] Notes

download Cse v Operating Systems [10cs53] Notes

of 150

Transcript of Cse v Operating Systems [10cs53] Notes

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    1/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 1

    PART -A

    UNIT -1 INTRODUCTION TO OPERATING SYSTEMS, SYSTEM STRUCTURES: What operating

    systems do;Computer System organization;Computer System architecture;OperatingSystem structure;

    OperatingSystem operations;Process management;Memory management;Storage management;Protection

    and security;Distributedsystem;Special-purposesystems;Computingenvironments.OperatingSystem

    Services;User -OperatingSystem interface;System calls;Types of system calls;System programs;Operating

    System designand implementation;OperatingSystem structure;Virtual machines;OperatingSystem

    generation;System boot.

    6 Hour U

    2 Process Management: Process concept;Process scheduling;Operationson processes;Inter-process

    communication.Multi-ThreadedProgramming:Overview;Multithreadingmodels;ThreadLibraries;

    Threadingissues. Process Scheduling:Basic concepts;Schedulingcriteria;Schedulingalgorithms;Multiple-

    Processor scheduling;Threadscheduling.7 Hours UNIT -3 PROCESS SYNCHRONIZATION: Synchroniz

    The Criticalsectionproblem;Petersons

    solution;Synchronization hardware;Semaphores;Classical problemsof synchronization;Monitors.

    7 Hours

    UNIT -4 DEADLOCKS: Deadlocks:System model;Deadlock characterization;Methods for handlingdeadlo

    Deadlock prevention;Deadlock avoidance;Deadlock detectionand recovery from deadlock.

    6 Hours

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    2/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 2

    PART -B

    UNIT -5

    MEMORY MANAGEMENT: Memory Management Strategies:Background;Swapping;Contiguous

    memory allocation;Paging;Structure of page table;Segmentation.Virtual Memory Management:

    Background;Demand paging;Copy-on-write;Page replacement;Allocation of frames;Thrashing.

    7 Hours

    UNIT -6 FILE SYSTEM, IMPLEMENTATION OF FILE SYSTEM: File System:File

    concept;Access methods;Directory structure;File system mounting;File sharing;Protection.

    ImplementingFile System:File system structure;File system implementation;Directory

    implementation;Allocation methods;Free space management.

    7 Hours

    UNIT-7 SECONDARY STORAGE STRUCTURES, PROTECTION: Mass storage structures;Disk

    structure;Disk attachment;Disk scheduling;Disk management;Swap space management.Protection:Goals of

    protection,Principles of protection,Domain of protection,Access matrix, Implementationof access 6 Hours

    UNIT -8 CASE STUDY: THE LINUX OPERATING SYSTEM: Linuxhistory;Design principles;Kernelmodules;Process management;Scheduling;Memory management;File systems,Inputand output;Inter-proces

    communication.6Hours

    TEXT BOOK:

    1. Operating System Principles Abraham Silberschatz, Peter Baer Galvin, Greg Gagne, 8th edition,Wiley-

    India,2009

    REFERENCE BOOKS:nd

    1. Operating Systems: A Concept Based Approach D.M Dhamdhere,2nd

    Edition, Tata McGraw-Hill, 20

    2. Operating Systems P.C.P. Bhatt, 2 Edition, PHI, 2006.rd

    3. Operating Systems Harvey M Deital, 3 Edition, Addison Wesley, 1990.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    3/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 3

    Table of Contents

    Topics Page no

    UNIT 1: INTRODUCTION TO OPERATING SYSTEMS, STRUCTURES

    1.1 WHAT OPERATING SYSTEM DO.

    1.2 COMPUTER SYSTEM ORGANIZATION.

    1.3 COMPUTER SYSTEM ARCHITECTURE.

    1.4 OPERATING SYSTEM STRUCTURE.

    1.5 OPERATING SYSTEM OPERATIONS.

    1.6 PROCESS MANAGEMENT.

    1.7 MEMORY MANAGEMENT.

    1.8 STORAGE MANAGEMENT.

    1.9 PROTECTION AND SECURITY.

    1 . 1 0 DISTRIBUTED SYSTEM.

    1.11 SPECIAL-PURPOSESYSTEMS.

    1.12 COMPUTING ENVIRONMENTS.

    1.13 OPERATING SYSTEM SERVICES.1.14 USER-OPERATINGSYSTEM INTERFACE.

    1.15 SYSTEM CALLS, TYPES OF SYSTEM CALLS.

    1.16 SYSTEM PROGRAMS.

    1.17 OPERATING SYSTEM DESIGN AND IMPLEMENTATION.

    1.18 OPERATING SYSTEM STRUCTURE.

    1.19 VIRTUAL MACHINES.

    1.20 OPERATING SYSTEM GENERATION.

    1.21 SYSTEM BOOT.

    1 -18

    UNIT 2: PROCESS MANAGEMENT 20-45

    2.1 PROCESS CONCEPT.

    2.2 PROCESS SCHEDULING.

    2.3 OPERATIONS ON PROCESSES.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    4/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 4

    2.4 INTER-PROCESSCOMMUNICATION.

    2.5 MULTI-THREADED PROGRAMMING.

    2.6 OVERVIEW; MULTITHREADING MODELS.

    2.7 THREAD LIBRARIES; THREADING ISSUES.

    2.8 PROCESS SCHEDULING: BASIC CONCEPTS.

    2.9 SCHEDULING CRITERIA.

    2.10 SCHEDULING ALGORITHMS.

    2.11 THREAD SCHEDULING.

    2.12 MULTIPLE-PROCESSORSCHEDULING.

    UNIT 3: PROCESS SYNCHRONIZATION 47-61

    3.1 SYNCHRONIZATION

    3.2 THE CRITICAL SECTION PROBLEM

    3.3 PETERSONSSOLUTION

    3.4 SYNCHRONIZATION HARDWARE

    3.5 SEMAPHORES

    3.6 CLASSICAL PROBLEMS OF SYNCHRONIZATION

    3.7 MONITORS

    UNIT 4: DEADLOCK 62 -71

    4.1 DEADLOCKS

    4.2 SYSTEM MODEL

    4.3 DEADLOCK CHARACTERIZATION

    4.4 METHODS FOR HANDLING DEADLOCKS

    4.5 DEADLOCK PREVENTION

    4.6 DEADLOCK AVOIDANCE

    4.7 DEADLOCK DETECTION

    4.8 RECOVERY FROM DEADLOCK

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    5/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 5

    UNIT 5 : STORAGE MANAGEMENT 73-95

    5.1 MEMORY MANAGEMENT STRATEGIES

    5.2 BACKGROUND

    5.3 SWAPPING

    5.4 CONTIGUOUS MEMORY ALLOCATION

    5.5 PAGING, STRUCTURE OF PAGE TABLE

    5.6 SEGMENTATION

    5.7 VIRTUAL MEMORY MANAGEMENT

    5.8 BACKGROUND,DEMAND PAGING

    5.9 COPY-ON-WRITE

    5.10 PAGE REPLACEMENT

    5.11 ALLOCATION OF FRAMES

    5.12 THRASHING.

    UNIT 6 : FILE SYSTEM INTERFACE 97-110

    . 6 . 1 FILE SYSTEM: FILE CONCEPT

    . 6 . 2 ACCESS METHODS

    . 6 . 3 DIRECTORY STRUCTURE

    . 6 . 4 FILE SYSTEM MOUNTING

    . 6 . 5 FILE SHARING; PROTECTION.

    . 6 . 6 IMPLEMENTING FILE SYSTEM

    . 6 . 7 FILE SYSTEM STRUCTURE

    . 6 . 8 FILE SYSTEM IMPLEMENTATION

    . 6 . 9 DIRECTORY IMPLEMENTATION

    . 6 . 1 0 ALLOCATION METHODS

    . 6 . 1 1 FREE SPACE MANAGEMENT.

    UNIT 7 : MASS STORAGE STRUCTURE 112-123

    7.1 MASS STORAGE STRUCTURES

    7.2 DISK STRUCTURE 7.3 DISK ATTACHMENT

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    6/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 6

    7.4 DISK SCHEDULING

    7.5 DISK MANAGEMENT

    7.6 SWAP SPACE MANAGEMENT

    7.7 PROTECTION: GOALS OF PROTECTION

    7.8 PRINCIPLES OF PROTECTION

    7.9 DOMAIN OF PROTECTION

    7.10 ACCESS MATRIX

    7.11 IMPLEMENTATION OF ACCESS MATRIX

    7.12 ACCESS CONTROL 7.13REVOCATION OF ACCESS RIGHTS

    7.14 CAPABILITY-BASED SYSTEM.

    UNIT 8: LINUX SYSTEM 125-138

    8.1 LINUX HISTORY

    8.2 DESIGN PRINCIPLES

    8.3 KERNEL MODULES

    8.4 PROCESS MANAGEMENT

    8.5 SCHEDULING

    8.6 MEMORY MANAGEMENT

    8.7 FILE SYSTEMS

    8.8 INPUT AND OUTPUT

    8.9 INTER-PROCESSCOMMUNICATION

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    7/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 7

    UNIT 1 INTRODUCTION TO OPERATING SYSTEMS, STRUCTURES

    1.22 WHAT OPERATING SYSTEM DO.1.23 COMPUTER SYSTEM ORGANIZATION.

    1.24 COMPUTER SYSTEM ARCHITECTURE.

    1.25 OPERATING SYSTEM STRUCTURE.

    1.26 OPERATING SYSTEM OPERATIONS.

    1.27 PROCESS MANAGEMENT.

    1.28 MEMORY MANAGEMENT.

    1.29 STORAGE MANAGEMENT.

    1.30 PROTECTION AND SECURITY.

    1 . 3 1 DISTRIBUTED SYSTEM .

    1.32 SPECIAL-PURPOSESYSTEMS.

    1.33 COMPUTING ENVIRONMENTS.

    1.34 OPERATING SYSTEM SERVICES.

    1.35 USER-OPERATING SYSTEM INTERFACE.

    1 . 3 6 SYSTEM CALLS, TYPES OF SYSTEM CALLS.

    1.37 SYSTEM PROGRAMS.

    1.38 OPERATING SYSTEM DESIGN AND IMPLEMENTATION.

    1.39 OPERATINGSYSTEM

    STR

    UCT

    URE.

    1.40 VIRTUAL MACHINES.

    1.41 OPERATING SYSTEM GENERATION.

    1.42 SYSTEM BOOT.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    8/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 8

    UNIT -1 INTRODUCTION TO OPERATING SYSTEMS, STRUCTURES

    1.1 WHAT OPERATING SYSTEM DO

    An OS is an intermediary between the user of the computer & the computer hardware. Itprovidesa basisfor applicationprogram & acts as an intermediary between user of computer & comphardware. The purpose of an OS is to providea environmentin which the user can execute the program in aconvenient& efficient manner.

    OS is an importantpart of almostevery computer systems. A computer system can be roughly dividedintofour components The Hardware The OS The applicationProgram The user

    The Hardware consistsof memory,CPU, ALU, I/Odevices, peripheralsdevices& storage devices. The applicationprogram mainly consistedof word processors,spread sheets,compilers& web browsedefinesthe ways in which the resources are used to solve the problemsof the users. The OS controls& co-ordinatesthe use of hardware among various applicationprogram for various us

    1.2 COMPUTER SYSTEM ORGANIZATION

    The following figureshows the conceptualview of a computer system

    Views OF OS

    1. UserViews:-Theuser view of the computer depends on the interfaceused.i. Some users may use PCs.In thisthe system is designedso that only one user can utilize the resource

    mostly for

    utilization.

    ease of use where the attention is mailnly on performances and not on the re

    ii. Some users may use a terminalconnected to a mainframeor minicomputers.iii. Other users may access the same computer through other terminals. Theseusers may share resourc

    exchange information. In this case the OS is designed to maximize resource utilization-soavailable CPU time, memory & I/Oare used efficiently.

    iv. Other users may sit at workstations,connected to the networks of other workstationand servers.case OS is designedto compromisebetween individual visibility & resource utilization.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    9/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 9

    2. SystemViews:i. We can view system as resource allocatori.e. a computer system has many resources that may be use

    solve a problem.The OS acts as a manager of these resources.The OS must decidehow to allo

    these resources to programs and the users so that it can operate the computer system efficientlyfairly.

    ii. A differentview of an OS is that it need to controlvarious I/Odevices& user programs i.e. an OS iscontrolprogram used to manage the executionof user program to prevent errors and improperuthe computer.

    iii. Resources can be eitherCPU Time, memory space,file storage space,I/Odevicesand so on.The OS must support the following tasks

    a. Provide the facility to create,modificationof programs & data files usingon editors.b. Access to compilersfor translatingthe user program from highlevel languageto machinelanguage.c. Provide a loaderprogram to move the compiledprogram code to computers memory for execution.

    d. Provides routinesthat handlethe detailsof I/Oprogramming.

    1.3 OPERATING SYSTEM ARCHITECTURE Mainframe System:a. Mainframe systems are mainly used for scientific & commercial applications.b. An OS may process its workload serially where the computer runs only one application

    or concurrently where computer runs many applications.Batch Systems:a. Early computers where physically largemachines.b. The common I/Pdevicesare card readers & tape drives.c. The common O/Pdevicesare line printers,tape drives & card punches.d. The user do not interactdirectly with computers but we use to prepare ajobwith the program,data & somecontrolinformation& submitit to the computer operator.e. Thejobwas mainly in the form punched cards.f. Atlatertimethe O/Pappeared and it consistedof resultalongwith dump of memory and registercontent fordebugging.

    The OS of these computers was very simple. Itsmajortask was to transfer controlfrom onejobto the next. ThOS was always residentin the memory.The processingofjobwas very slow. To improvethe processingspeedoperators batched together thejobswith similar needs and processed it through the computers.This is called BaSystems. In batch systems the CPU may be idle for some timebecause the speed of the mechanicaldevicesslowcompared to the electronicdevices. Laterimprovementin technology and introductionof disks resultedin faster I/Odevices. The introductionof disks allowed the OS to store all thejobson the disk. The OS couldperform theschedulingto use the resources and perform the task efficiently.

    Disadvantages of Batch Systems:

    1. Turn around timecan be largefrom user.2. Difficultto debug the program.3. Ajobcan enter intoinfinite loop.4. Ajobcouldcorrupt the monitor.5. Due to lack of protectionscheme,onejobmay affect the pendingjobs.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    10/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 10

    Multi programmed System:a. If there are two or more programs in the memory at the same timesharingthe processor,thisis referred as mprogrammed OS.b. Itin

    creasesthe CPU

    utilization byo

    rgani

    zingthejobsso that the CPU will always have onejobto exe

    cute.

    c. Jobs enteringthe systems are kept in memory.d. OS picks thejobfrom memory & it executes it.e. Having severaljobsin the memory at the same timerequiressome form of memory management.f. Multi programmed systems monitorsthe state of all active program and system resources and ensures that CPnever idle until there are nojobs.g. While executinga particularjob, if thejobhas to wait for any task like I/Ooperationto be completethen thewill switch to some otherjobsand starts executingit and when the firstjobfinishes waiting the CPU will switcback to that.h. This will keep the CPU & I/Outilization busy. The following figureshows the memory layoutof multiprogrammed OS

    Time sharing Systems:a. Time sharingsystem or multi taskingis logical extensionof multi programmingsystems.The CPU executesmultiplejobsby switching between them but the switching occurs so frequently that user can interactwith eacprogram while it is running.b. An interactive& hands on system providesdirectcommunicationbetween the user and the system. The usergive the instructionto the OS or program directly through key board or mouse and waits for immediateresults.c. A timeshared system allows multiple users to use the computer simultaneously. Since each actionor commare short in timeshared systems only a small CPU timewill be available for each of the user.d. A timeshared systems uses CPU schedulingand multi programmingto provideeach user a small portionofshared computers.When a process executes it will be executingfor a short timebefore it finishes or need to peI/O.I/Ois interactivei.e. O/Pis to a display for the user and the I/Ois from a keyboard,mouse etc.e. Since it has to maintainseveraljobsat a time, system shouldhave memory management & protection.f. Time sharingsystems are complex than the multi programmed systems.Since severaljobsare kept in memothey need memory management and protection.To obtainless response timejobsare swapped in and out of mamemory to disk. So disk will serve as backingstore for mainmemory.This can be achievedby usinga techniqcalled virtual memory that allows for the executionofjobi.e. not completein memory.g. Time sharingsystem shouldalso providea file system & file system resideson collection of disks so thisdisk management.Itsupports concurrent execution,jobsynchronization& communication.

    II. DESKTOP SYSTEMS:

    Pcsappeared in 1970sand duringthisthey lackedthe feature needed to protect an OS from user prog

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    11/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 11

    & they even lack multi user nor multi tasking. The goalspf those OS changed laterwith the timeand new systems includesMicrosoft Windows & ApMacintosh. The Apple MacintoshOS ported to more advanced hardware & includesnew features like virtual memmulti tasking.

    Micro computers are developedfor singleuser in 1970s& they can accommodate software witlargecapacity & greater speeds.MS-DOS is an examplefor micro computer OS & are used by commercial,educational,government enterprises.

    III. Multi Processor Systems:

    Multi processor systems includemore than one processor in closecommunication. They share computer bus,the clock, m/y & peripheraldevices. Two processes can run in parallel. Multi processor systems are of two types a. Symmetric Multi processors ( SMP) b. Asymmetric Multi processors. In symmetric multi processing,each processors runs an identical copy of OS and they communicatewitone another as needed.All the CPU shares the common memory. In asymmetricmulti processing,each processors is assigneda specific task. Ituses a master slaverelationship.A master processor controlsthe system. The master processors schedulesand allocateswork to slaprocessors.The following figureshows asymmetricmulti processors. SMP means al processors are peers i.e. no master slave relationshipexists between processors.Eachprocessors concurrently runs a copy of OS. The differencesbetween symmetric & asymmetricmulti processingmay be resultof eitherH/wor S/wSpecial H/wcan differentiatethe multiple processors or the S/wcan be writtento allow only master & multipleslaves.

    Advantages of Multi Processor Systems:1. IncreasedThroughput:-By increasingthe Number of processors we can get more work done in less time. W

    multiple process co operate on task, a certainamount of overhead is incurredin keepingall parts workingcorrectly.

    2. EconomyOfScale:-Multiprocessor system can save more money than multiple singleprocessor,since theyshare peripherals,mass storage & power supplies. If many programs operate on same data,they will be stoon one disk & all processors can share them insteadof maintainingdata on several systems.

    3. IncreasedReliability:-Ifa program is distributedproperly on several processors,than the failure of oneprocessor will not haltthe system but it only slows down.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    12/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 12

    1.4 OPERATING SYSTEM STRUCTURES

    PROCESS CONTROL & JOB CONTROL

    A system call can be used to terminatethe program eithernormally or abnormally. Reasons for abnormterminationare dump of m/y,error message generated etc. Debugger is mainly used to determineproblemof the dump & returns back the dump to the OS. In normalor abnormalsituationsthe OS must transfer the controlto the command interpretersystem. In batch system the command interpreterterminatesthe executionofjob& continueswith the nextjob Some systems use controlcards to indicatethe special recovery actionto be taken in case of errors. Normal & abnormalterminationcan be combinedat some errors level. Error level is definedbefore & hcommand interpreteruses thiserror level to determinenext actionautomatically.

    MS-DOS:

    MS-DOS is an exampleof single tasking system, which has command interpreter system i.e. invokedwhcomputer is started.To run a program MS-DOS uses simple method.Itdoes not create a process when one p

    is running MS-DOS the program into m/y & gives the program as muchas possible. It lacks the gmultitaskingcapabilities.

    BSD:FreeBSD is an exampleof multitaskingsystem. In free BSD the command interpretermay continuerunnwhile other program is executing.FORK is used to create new process.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    13/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 13

    1.5 OPERATING SYSTEM OPERATIONS

    Modern OS supports all system components.The system components are,

    1. Process Management.2. Main M/y Management.3. File Management.4. Secondary Storage Management.5. I/OSystem management.6. Networking.7. ProtectionSystem.8. Command InterpreterSystem.

    1.6 PROCESS MANAGEMENT

    A process is a program in execution. A process abstractionis a fundamentalOS mechanismfor the management of concurrent program

    execution. The OS responds by creatingprocess. Process requirescertainresources like CPU time, M/y,I/Odevices. Theseresources are allocatedto theprocess when it created or while it is running. When process terminatesthe process reclaims all the reusableresources. Process refers to the executionof M/cinstructions. A program by itself is not a process but is a passiveentity.

    The OS is responsiblefor the following activities of the process management, Creating& destroyingof the user & system process . Allocating H/wresources among the processes.

    Controlling the progress of the process. Provides mechanismfor process communication. Provides mechanismfor deadlock handling.

    1.7 MEMORY MANAGEMENT

    Main M/y is the centre to the operationof the modern computer. Main M/y is the array of bytes rangingfrom hundreds of thousands to billions. Each byte will have theiown address. The centralprocessor reads the instructionfrom mainM/y duringinstructionfetch cycle & it both readswrites the data duringthe data-fetch cycle. The I/Ooperationreads and writes data in mainM/y. The mainM/y is generally a largestorage devicein which a CPU can address & access directly. When a program is to be executed it must be loadedintomemory & mapped to absoluteaddress.Whenexecutingit access the data & instructionfrom M/y by generatingabsoluteaddress.When the program terminaavailable M/y will be returned back. To improvethe utilization of CPU & the response timeseveral program will be kept in M/y. Several M/y management scheme are available & selectiondepends on the H/wdesignof the system. The OS is responsiblefor the following activities. Keepingtrack of which part of the M/y is used & by whom. Deciding which process are to be loadedintoM/y. Allocating & de allocatingM/y space as needed.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    14/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 14

    et

    c.

    File Management:

    File management is one of the most visible component of an OS.Computer stores data on differenttypes of physical medialike MagneticDisks, Magnetictapes,optical

    For convenientuse of the computer system the OS providesuniform logical view of informationstoragThe OS maps file on to physical media& access these files via storage devices.A file is logical collection of information.File consistsof both program & data.Data files may be numeric, alphabetsor alphanumeric.Files can be organizedintodirectories.The OS is responsiblefor the following activities,Creating& deletingof files.Creating& deletingdirectories.Supportingprimitives for manipulatingfiles & directories.Mapingfiles onto secondary storage.Backing up files on stablestorage media.

    1.8 STORAGE MANAGEMENT Is a mechanismwhere the computer system may store informationin a way that it can be retrievedlater They are used to store both data & programs. The programs & data are stored in mainmemory. Since the size of the M/y is small & volatile Secondary storage devicesis used. activities,

    Magneticdisk is centralimportanceof computer system. The OS is responsiblefor the following

    Free space management.

    Storage allocation.

    Disk scheduling.The entirespeed of computer system depends on the speed of the disk sub system.

    I/O System Management: Each I/odevicehas a devicehandlerthat residesin separate process associatedwith that device. The I/Omanagement consistsof, A M/y management component that includebuffering,, caching& spooling. General device-driver interface. Drivers for specific H/wdevice.

    Networking :

    Networkingenablesusers to share resources & speed up computations.

    The process communicateswith one another through various communicationlines like high speed buses or N/w.Following parameters are consideredwhile designingthe N/w, Topology of N/w. Type of N/w. Physical media. Communicationprotocol, Routing algorithms.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    15/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 15

    1.9 PROTECTION AND SECURITY

    Modern computer system supports many users & allows the concurrent executionof multiple processeorganizationrely on computers to store information. Itnecessary that the information& devicesmust be protecfrom unauthorizedusers or processors. The protectionis a mechanismfor controllingthe access of program,processes or users to the resourcedefinedby a computer system. Protectionmechanismare implementedin OS to support various security policies. The goalof security system is to authenticatetheiraccess to any object. Protectioncan improvereliability by detectinglatenterrors at the interfaceB/wcomponent sub system. Protectiondomainsare extensionsof H/wsupervisormode ability.

    1.10 DISTRIBUTED SYSTEMS A distributedsystem is one in which H/wor S/wcomponents locatedat the networked computerscommunicate& co ordinatetheiractionsonly by passingmessages. A distributedsystems looks to its user like an ordinary OS but runs on multiple, IndependentCPUs.

    Distributedsystems depends on networkingfor theirfunctionality which allows for communicationso tdistributedsystems are ableto share computationaltasks and providesrich set of features to users. N/wmay vary by the protocolsused,distancebetween nodes & transport media.Protocols->TCP/IP,Aetc.Network-> LAN, MAN, WAN etc.TransportMedia->copper wires, opticalfibers & wireless transmission

    Client-Server Systems:

    Since PCsare faster,power full, cheaper etc.designershave shiftedaway from the centralizedsystemarchitecture. User-interfacefunctionality that used to be handledby centralizedsystem is handledbyPCs.

    So the centralizedsystem today act as server program to satisfy the requests of client. Server system c

    classified as followsc. Computer-ServerSystem:-Providesan interfaceto which client can send requests to perform some actions,inresponse to which they execute the actionand send back resultto the client.d. File-ServerSystems:-Providesa file system interfacewhere clients can create,update,read & deletefiles.

    Peer-to-Peer Systems:

    time.

    PCsare introducedin 1970sthey are consideredas standalonecomputers i.e. only one user can use it

    With wide spread use of internetPCswere connected to computer networks.With the introductionof the web in mid1990sN/wconnectivity became an essentialcomponent of a

    computer system. All modern PCs& workstationcan run a web. Os alsoincludessystem software that enablesthe compto access the web. In distributedsystems or loosely coupledcouplesystems,the processor can communicatewith one anothrough various communicationlines like highspeed buses or telephoneslines. A N/wOS which has taken the concept of N/w& distributedsystem which providesfeatures fir file shaacross the N/wand alsoprovidescommunicationwhich allows differentprocessors on differentcomputers to sresources.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    16/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 16

    Advantages of Distributed Systems:

    1. Resource sharing.2. Higher reliability. 3.Better price performance ratio. 4.Shorterresponse time. 5.Hthroughput.6.Incrementalgrowth

    1.11 SPECIAL-PURPOSESystems SYSTEMS. Clustered

    Likeparallel systems the clusteredsystems will have multiple CPU but they are composed of two or mindividual system coupledtogether. Clusteredsystems share storage & closely linked via LAN N/w. Clustering is usually done to providehighavailability. Clusteredsystems are integratedwith H/w& S/w.H/wclustersmeans sharingof highperformance disS/wclustersare in the form of unified controlof a computer system in a cluster. A layer of S/wclusterruns on the clusternodes.Each node can monitorone or more of the others.If thmonitoredM/cfails the monitoringM/ctake ownershipof its storage and restart the applicationthat were runnon failed M/c. Clusteredsystems can be categorizedintotwo groups

    Asymmetric Clustering & Symmetric clustering

    In asymmetricclusteringone M/cis in hot standby mode while others are runningthe application.Thestandby M/cdoes nothingbut it monitorsthe active server. If the server fails the hot standby M/cbecomes the server. In symmetric mode two or more hosts are runningthe Application & they monitoreach other.This modmore efficient since it uses all the available H/w. Parallel clusteringand clusteringover a LAN is alsoavailable in clustering. Parallel clusteringallowsmultiple hosts to access the same data on shared storage. Clustering providesbetter reliability than the multi processor systems. Itprovidesall the key advantages of a distributedsystems.

    Clustering technology is changing& includeglobalclustersin which M/ccouldbe anywhere in the wo

    Real-Time Systems

    Real time system is onewhich wereoriginallyused to control autonomous systems like satellites,hydroelectricdams etc. Real timesystem is one that must react to I/p& responds to them quickly. A realtimesystem shouldnot be latein response to one event. A realtimeshouldhave well definedtimeconstraints.

    Real timesystems are of two types Hard Real Time Systems Soft Real Time Systems

    A hard realtimesystem guarantees that the critical tasks to be completedon time. This goalrequiresthdelaysin the system be bounded from the retrieval of stored data to timethat it takes the OS to finish the reque In soft realtimesystem is a less restrictive one where a critical realtimetask gets priority over other tasretainsthe property until it completes.Soft realtimesystem is achievablegoalthat can be mixed with other typsystems.They have limited utility than hard realtimesystems. Soft realtimesystems are used in area of multimedia, virtual reality & advanced scientific projects.Itcbe used in roboticsor industrial controlsdue to lack of deadlinesupport. Real timeOS uses priority schedulingalgorithmto meet the response requirementof a realtimeapplica Soft realtimerequirestwo conditionsto implement,CPU schedulingmust be priority based & dispatchlatency shouldbe small. The primary objectiveof file management in realtimesystems is usually speed of access, rather thanefficient utilization of secondary storage.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    17/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 17

    1.12 COMPUTING ENVIRONMENTS

    Different types of computingenvironmentsare:

    Traditional Computing. Web BasedComputing. EmbeddedComputing.

    Traditional Computing Typical office environmentuses traditionalcomputing.Normal PC is used intraditionalcomputingenvironment.N/wcomputers are essentialterminalsthat understand web based computindomesticapplicationmost of the user had a singlecomputer with internetconnection.Cost of accessinginternehigh. Web Based Computing has increasedthe emphasison N/w.Web based computinguses PC, handheld& cell phones.One of the feature of thistype is loadbalancing.In loadbalancing,N/wconnectionis distributeamong a poolof similar servers. Embedded computing uses realtimeOS. Application of embedded computingis car engines,

    manufacturingrobots,microwave ovens.This type of system provideslimited features.

    1.13 OPERATING SYSTEM SERVICES:

    An OS providesservices for the executionof the programs and the users of such programs.The services providone OS may be differentfrom other OS. OS makes the programmingtask easier. The common services providthe OS are

    1. ProgramExecution:-TheOS must ableto loadthe program intomemory & run that program.The programend its executioneithernormally or abnormally.

    2. I/OOperation:-Aprogram runningmay requireany I/O.This I/Omay be a file or a specific deviceusers cancontrolthe I/Odevicedirectly so the OS must providea means for controllingI/Odevices.

    3. FileSystemInterface:-Programneed to read or write a file. The OS shouldprovidepermissionfor the creatiodeletionof files by names.

    4. Communication:-Incertainsituationone process may need to exchange informationwith another process.TcommunicationMay takes placein two ways.

    a. Betweenthe processes executingon the same computer.b. Between the processes executing ondifferent computer that areconnected by a network.

    communicationcan be implementedvia shared memory or by OS.5. ErrorDetection:-Errorsmay occur in CPU, I/Odevicesor in M/y H/w.The OS constantly needs to be a

    of possible errors.For eachtype of errors the OS should take appropriate actions to ensure corrconsistentcomputing.

    OS with multiple users providesthe following services,a. Resource Allocation:-Whenmultiple users logsonto the system or when multiplejobsare running,resourcesbe allocatedto each of them.The OS manages differenttypes of OS resources.Some resources may need somespecial allocationcodes & others may have some generalrequest & releasecode.b. Accounting:-Weneed to keep track of which users use how many & what kind of resources.This record keemay be used for accounting.This accountingdata may be used for statisticsor billing. Itcan alsobe used to imsystem efficiency.c. Protection:-Protectionensures that all the access to the system are controlled.Security starts with each userhavingauthenticatedto the system, usually by means of a password.External I/Odevicesmust alsobe protectefrom invalid access. In multi process environmentit is possiblethat one process may interfacewith the other orthe OS, so protectionis required.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    18/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 18

    1.14 USER OPERATING SYSTEM INTERFACE Command Interpreter System

    Command interpretersystem between the user & the OS. Itis a system program to the OS. Command interpreteris a special program in UNIX & MS DOS OS i.e. runningwhen the user logson.

    Many commands are givento the OS through controlstatements when the user logson,a program that& interpretscontrolstatements is executed automatically. This program is sometimescalled the controlcardinterpreteror command line interpreterand is alsocalled as shell. The command statements themselvesdealwith process creation& management,I/Ohandling,secondastorage management,mainmemory management,file system access, protection& N/w.

    1.15 SYSTEM CALLS

    System providesinterfacebetween the process & the OS. The calls are generally available as assembly languageinstruction& certainsystem allow system callsmade directly from a highlevel languageprogram. Several languagehave been definedto replaceassembly languageprogram. A system call instructiongenerates an interruptand allows OS to gaincontrolof the processors.

    System calls occur in differentways dependingon the computer.Some timemore informationis needeidentify the desiredsystem call. The exact type & amount of informationneeded may vary accordingto theparticularOS & call.

    TYPES OF SYSTEM CALLSPASSING PARAMETERS TO OS

    Three generalmethods are used to pass the parameters to the OS. The simplestapproach is to pass the parameters in registers.In some there can be more parameters thanregister.In these the parameters are generally in a block or tablein m/y and the address of the block is passed aparameters in register.This approach used by Linux.

    Parameters can alsobe placedor pushed onto stack by the program & popped off the stack by the OS. Some OS prefer the block or stack methods,because those approaches do not limit the number or lengtparameters beingpassed. System calls may be grouped roughly into5 categories

    . Process control.

    . File management.

    . Device management.

    . Informationmaintenance.

    . Communication.

    1.16 SYSTEM PROGRAMS

    Many system calls are used to transfer informationbetween user program & OS. Example:-Mostsystem

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    19/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 19

    have the system calls to return the current time& date,number of current users,version number of OS, amountfree m/y or disk space & so on. In additionthe OS keeps informationabout all its processes & there are system calls to access

    thisinformation. COMMUNICATION:-There are two modes of communication,1. MessagePassingModels: In thisinformationis exchanged usinginter-processcommunicationfacility providedby OS. Before communicationthe connectionshouldbe opened. The name of the other communicatingparty shouldbe known, it ca be on the same computer or it can banother computer connected by a computer network. Each computer in a network may have a host name like IP name similarly each process can have a procname which can be translatedintoequivalentidentifier by OS. The get host id & process id system call do thistranslation.Theseidentifiers are then passed to the opencloseconnectionsystem calls.

    call.

    The recipientprocess must give its permissionfor communicationto take placewith an accept connect

    Most processes receive the connectionthrough special purpose system program dedicatedfor that purpcalled daemons.The daemon on the server sideis called server daemon & the daemon on the client sideis calleclient daemon.

    2. SharedMemory: In thisthe processes uses the map m/y system calls to gainaccess to m/y owned by another process. The OS triesto prevent one process from accessinganother process m/y. In shared m/y thisrestrictionis eliminatedand they exchange informationby readingand writing data ishared areas.Theseareas are locatedby these processes and not under OS control. They shouldensure that they are not writing to same m/y area.

    Both these types are commonly used in OS and some even implementboth. Message passingis useful when small number of data need to be exchanged since no conflicts are to beavoidedand it is easierto implementthan in shared m/y.Shared m/y allows maximum speed and conveniencecommunicationas it is done at m/y speed when within a computer.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    20/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 20

    1.17 OPERATING SYSTEM DESIGN AND IMPLEMENTATION FILE MANAGEMENT

    System calls can be used to create & deletingof files. System calls may requirethe name of the files wiattributesfor creating& deletingof files.

    Other operationmay involve the readingof the file, write & repositionthe file after it is opened. Finally we need to closethe file. For directoriessome set of operationare to be performed.Sometimeswe requireto reset some of theattributeson files & directories.The system call get file attribute& set file attributeare used for thistype ofoperation.

    DEVICE MANAGEMENT:

    The system calls are alsoused for accessingdevices. Many of the system calls used for files are alsoused for devices. In multi user environmentthe requirementare made to use the device. After usingthe devicemust bereleasedusingreleasesystem call the deviceis free to be used by another user.Thesefunctionare similar to opclosesystem calls of files.

    Read, write & repositionsystem calls may be used with devices. MS-DOS & UNIX merge the I/Odevices& the files to form file services structure.In file devicestructI/Odevicesare identifiedby file names.

    1.18 OPERATING SYSTEM STRUCTURES

    Modern OS is large& complex. OS consistsof differenttypes of components. Thesecomponents are interconnected& meldedintokernel. For designingthe system differenttypes of structures are used.They are, Simple structures. Layeredstructured.

    Micro kernels

    Simple Structures

    Simple structure OS are small, simple & limited systems. The structure is not well defined MS-DOS is an exampleof simple structure OS. MS-DOS layer structure is shown below

    UNIX consistedof two separate modules

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    21/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 21

    a. Kernel b. The system programs. Kernelis further separated intoseriesof interfaces& devicedrivers which were added & expanded as tUNIX evolvedover years. The kernelalsoprovidesthe CPU scheduling,file system, m/y management & other OS functionthrougsystem calls. System calls defineAPI to UNIX and system programs commonly available definesthe user interface.programmer and the user interfacedeterminesthe context that the kernelmust support. New versions of UNIX are designedto support more advanced H/w.the OS can be broken down intolanumber of smaller components which are more appropriatethan the original MS-DOS.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    22/150CITSTUDENTS.IN 22

    Operating Systems 10CSS

    Layered Approach

    _ ...- ------- - IC3..yE3r f'..J

    .

    _.......--.....-

    -

    usE:=tr ir"l1:rlc:::.e:=

    ------

    )

    --

    --.,,"'\

    //--- /

    -------

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    23/150CITSTUDENTS.IN 23

    Operating Systems 10CS53

    In thisOS is dividedintonumber of layers, where one layer is built on the top of another layer. The botlayer is hardware and higherlayer is the user interface.data.

    An OS is an implementationof abstract objec

    ti.e. the encapsulationof data & ope

    rationto manipulate

    The mainadvantage of layeredapproach is the modularity i.e. each layer uses the services & functionsprovidedby the lower layer. This approach simplifies the debugging& verification. Once first layer is debuggecorrect functionality is guaranteed while debuggingthe second layer. If an error is identifiedthen it is a problemthat layer because the layer belowit is already debugged. Each layer is designedwith only the operationsprovidedby the lower level layers. Each layer triesto hidesome data structures,operations& hardware from the higherlevel layers. A problemwith layeredimplementationis that they are less efficient then the other types.

    Micro Kernels Micro kernelis a small Os which providesthe foundationfor modularextensions.

    The mainfunctionof the micro kernelsis to providecommunicationfacilities between the current progand various services that are runningin user space. This approach was supposed to providea highdegree of flexibility and modularity. This benefitsof thisapproach includesthe ease of extendingOS. All the new services are added to thespace & do not need the modificationof kernel. This approach alsoprovidesmore security & reliability. Most of the services will be runningas user process rather than the kernelprocess. This was popularizedby use in Mach OS. Micro kernelsin Windows NT providesportability and modularity. Kernel is surrounded by a number ocompact sub systems so that task of implementingNT on variety of platformis easy. Micro kernelarchitectureassignonly a few essentialfunctionsto the kernelincluding address space,IP

    basic scheduling. QNX is the RTOS i.e. alsobased on micro kerneldesign.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    24/150CITSTUDENTS.IN 24

    Operating Systems 10CS53

    1.19 VIRTUAL MACHINES

    A virtual machinetakes the layeredapproach to its logical conclusion. Ittreats hardware and the operatingsystkernelas though they were all hardware.A virtual machineprovidesan interfaceidentical to the underlyingba

    hardware.The operatingsystem creates the illusion of multiple processes,each executingon its own processorits own (virtual) memory.The resources of the physical computer are shared to create the virtual machines.CPschedulingcan create the appearance that users have theirown processor.Spoolingand a file system can provivirtual card readers and virtual line printers.A normaluser time-sharingterminalserves as the virtual machineoperatorsconsole.

    NON-VIRTUALMACHINE VIRTUALMACHINE

    Advantages and Disadvantages of Virtual Machines

    The virtual-machineconcept providescompleteprotectionof system resources since each virtual machisolatedfrom all other virtual machines.This isolation, however, permitsno directsharingof resources. A virtual-machinesystem is a perfect vehicle for operating-systemsresearch and development.Systemdevelopmentis done on the virtual machine,insteadof on a physical machineand so does not disruptnormalsyoperation. The virtual machineconcept is difficult to implementdue to the effort requiredto providean exact dupto the underlyingmachine.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    25/150CITSTUDENTS.IN 25

    Operating Systems 10CS53

    Java Virtual Machine

    Compiled Java programs are platform-neutralbytecodes executed by a Java Virtual Machine (JVM). JVM consistsof -class loader-class verifier -runtimeinterpreter Just-In-Time(JIT)

    compile

    rsin

    creaseperformance

    JAVA VIRTUAL MACHINE

    1.20 OPERATING SYSTEM GENERATION;

    User goalsoperatingsystem shouldbe convenientto use,easy to learn, reliable, safe, and fast.o System goalsoperatingsystem shouldbe easy to design,implement,and maintain, as well as flexible, relierror-free,and efficient Mechanismsdeterminehow to do something,policies decidewhat will be done.o The separationof policy from mechanismis a very importantprinciple, it allows maximum flexibility if poldecisionsare to be changed later

    Traditionally writtenin assembly language,operatingsystems can now be writtenin higher-levellangu Code writtenin a high-level language:

    o can be writtenfaster. o is more compact. o is easierto understand and debug.

    An operatingsystem is far easiertoport (move to some other hardware) if it is writtenin a high-levellanguage.

    1.21 SYSTEM BOOT

    Operatingsystems are designedto run on any of a class of machines;the system must be configuredfo

    specific computer site. SYSGEN program obtainsinformationconcerningthe specific configurationof the hardware system. Booting startinga computer by loadingthe kernel. Bootstrap program code stored in ROM that is ableto locatethe kernel, loadit intomemory,and starexecution.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    26/150CITSTUDENTS.IN 26

    Operating Systems 10CS53

    IMPORTANT QUESTIONS

    1. What are the three mainpurposes of an operatingsystem?2. What is the mainadvantage of multip

    rog

    ramming

    ?

    3. What are the maindifferencesbetween operatingsystems for mainframecomputers and personalcomputers?4. Define the essentialpropertiesof the following types of operatingsystems:a. Batchb. Interactivec. Time sharingd. Real timee. Networkf. Distributed. What are the differencesbetween a trap and an interrupt?What is the use of each function?. What are the five majoractivities of an operatingsystem in regard to process management?

    . What are the three majoractivities of an operatingsystem in regard to secondary-storage management?. Listfive services providedby an operatingsystem.. What is the mainadvantage of the layeredapproach to system design?

    . 10. What is the mainadvantage for an operating-systemdesignerof usingavirtual-machinearchitecture?Wis the mainadvantage for a user?

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    27/150CITSTUDENTS.IN 27

    Operating Systems 10CS53

    UNIT 2 PROCESS MANAGEMENT

    TOPICS

    2.13 PROCESS CONCEPT.2.14 PROCESS SCHEDULING.2.15 OPERATIONS ON PROCESSES.2.16 INTER-PROCESSCOMMUNICATION.2.17 MULTI-THREADED PROGRAMM ING.2.18 OVERVIEW; MULTITHREADING MODELS.2.19 THREAD LIBRARIES; THREADING ISSUES.2.20 PROCESS SCHEDULING: BASIC CONCEPTS.2.21 SCHEDULING CRITERIA.2.22 SCHEDULING ALGORITHMS.2.23 THREAD SCHEDULING.

    2.24 MULTIPLE-PROCESSORSCHEDULING.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    28/150CITSTUDENTS.IN 28

    Operating Systems 10CS53

    2.1 PROCESS CONCEPTS

    Processes & Programs:

    Process is a dynamic entity. A process is a sequence of instructionexecutionprocess exists in a limitedof time. Two or more process may execute the same program by usingits own data & resources. A program is a staticentity which is made up of program statement.Program containsthe instruction. Aprogram exists in a singlespace.A program does not execute by itself. A process generally consistsof a process stack which consistsof temporary data & data sectionwhichconsistsof globalvariables. Italsocontainsprogram counter which represents the current activities. A process is more than the program code which is alsocalled text section.

    Process State:

    Theprocess state consist of everything necessary to resume the process execution if it is somehow puttemporarily. The process state consistsof at leastfollowing:

    x Code for the program.x Program's staticdata.x Program's dynamic data.x Program's procedure call stack.x Contents of generalpurpose registers.x Contents of program counter (PC)x Contents of program status word (PSW).x OperatingSystems resource in use.

    2.2 PROCESS SCHEDULING

    PROCESS SCHEDULING QUEUES

    The following are the differenttypes of process schedulingqueues.

    1. Job queue set of all processes in the system2. Ready queue set of all processes residingin mainmemory,ready and waiting to execute3. Device queues set of processes waiting for an I/Odevice4. Processes migrateamong the various queues

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    29/150CITSTUDENTS.IN 29

    Operating Systems 10CS53

    Ready Queue And Various I/O Device Queues

    Ready Queue:The process that are placedin mainm/y and are already and waiting to executes are placedin a list called t

    ready queue.This is in the form of linked list.Ready queue header containspointerto the first & final PCB inlist.Each PCB containsa pointerfield that pointsnext PCB in ready queue.

    Device Queue:Thelist of processes waiting for a particularI/Odeviceis called device. When the CPU is alloto a process it may execute for some time& may quitor interruptedor wait for the occurrence of a particularlike completionof an I/Orequest but the I/Omay be busy with some other processes.In thiscase the processwait for I/O.This will be placedin devicequeue.Each devicewill have its own queue.The process schedulingis represented usinga queuingdiagram.Queues are represented by the rectangularbox

    resources they need are represented by circles. Itcontainstwo queues ready queue & devicequeues.Once theprocess is assignedto CPU and is executingthe following events can occur,

    1.20 Itcan execute an I/Orequest and is placedin I/Oqueue.1.21 The process can create a sub process & wait for its termination.1.22 The process may be removed from the CPU as a resultof interruptand can be put back intoready

    queue.

    Schedulers:

    The following are the differenttype of schedulers

    1. Long-term scheduler (or job scheduler) selectswhich processes shouldbe brought intothe ready queu2. Short-term scheduler (or CPU scheduler) selectswhich process shouldbe executed next and allocates3. Medium-term schedulers

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    30/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 30

    -> Short-term scheduleris invokedvery frequently (milliseconds) . (must be fast)

    -> Long-termscheduleris invokedvery infrequently (seconds,minutes)(may be slow)

    -> The long-termschedulercontrolsthe degree of multiprogramming

    ->Processes can be describedas either:

    x I/O-boundprocess spends more timedoingI/Othan computations,many short CPU bursts

    CPU-bound process spends more time doing computations; few very long CPU bursts

    2.3 OPERATION ON PROCESS

    Process Creation

    In general-purpose systems, some way is needed to create processes as needed duringoperation. There arprincipal events ledto processes creation.

    x System initialization.x Executionof a process CreationSystem calls by a runningprocess.x A user request to create a new process.x Initializationof a batchjob.

    Foreground processes interact with users.Background processes that stay in background sleeping but suspringing to life to handleactivity such as email, webpage,printing,and so on. Backgroundprocesses aredaemons.This call creates an exact cloneof the calling process.A process may create a new process by someprocess such as 'fork'. Itchoose to does so, creatingprocess is called parent process and the created one is cachild processes.Only one parent is needed to create a child process.Note that unlike plantsand animals thsexualrepresentation, a process has only oneparent. This creation of process (processes) yieldsa hierastructure of processes like one in the figure. Noticethat each child has only one parent but each parent mamany children. After the fork, the two processes,the parent and the child, have the same memory image,theenvironmentstringsand the same open files. After a process is created,both the parent and child have thedistinctaddress space. If eitherprocess changes a word in its address space, the change is not visible to thprocess.

    Following are some reasons for creationof a process

    x User logson.x User starts a program.x Operatingsystems creates process to provideservice, e.g., to manage printer.x Some program starts another process,e.g., Netscape callsxv to display a picture.

    Process Termination

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    31/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 31

    A process terminateswhen it finishes executing its last statement. Its resources are returned to the systepurged from any system lists or tables,and its process controlblock (PCB) is erased i.e., the PCB'smemory sreturned to a free memory pool.The new process terminatesthe existing process,usually due to following reas

    x Normal Exist Most processes terminatesbecause they have done theirjob. This call is exist in UNIX. x Error EWhen process discovers a fatal error.For example, a user triesto compilea program that does not exist. x FataError An error caused by process due to a bug in program for example, executingan illegal instruction, referrnon-existingmemory or dividing by zero. x Killed by another Process A process executes a system call tellingOperatingSystems to terminatesome other process.In UNIX, thiscall is kill. In x some systems when a procekills all processes it created are killed as well (UNIX does not work thisway).

    Process States :A process goes through a seriesof discreteprocess states.

    x New State The process beingcreated.x Terminated State The process has finished execution.x Blocked

    (waiting) State When a process blocks, it does so because logically it cannot

    continue,typically because it is waiting for inputthat is not yet available. Formally, a process is saidtoblockedif it is waiting for some event to happen (such as an I/Ocompletion)before it can proceed.In tstate a process is unableto run until some externalevent happens.

    x Running State A process is saidt be runningif it currently has the CPU, that is, actually usingthe CPU at thatparticularinstant.x Ready State A process is saidto be ready if it use a CPU if one were available. Itis runabltemporarily stopped to letanother process run.

    Logically,the 'Running'and 'Ready' states are similar. In both cases the process is willing to run, only in the ca'Ready' state,there is temporarily no CPU available for it.The 'Blocked' state is differentfrom the 'Running'an'Ready' states in that the process cannot run, even if the CPU is available.

    Process Control Block

    A process in an operatingsystem is represented by a data structure known as a process controlblock (PCB) or

    process descriptor.The PCB containsimportantinformationabout the specific process including x The current stthe process i.e., whether it is ready,running,waiting, or whatever.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    32/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 32

    x Unique identification of the process in order to track "which is which" information.x A pointerto parent process.x Similarly, a pointerto child process (if it exists).x The

    priorityof process (a part of CPU s

    chedulinginfo

    rmation).

    x Pointersto locatememory of processes.x A registersave area.x The processor it is runningon.

    The PCB is a certainstore that allows the operatingsystems to locatekey informationabout a process.ThuPCB is the data structure that definesa process to the operatingsystems.

    The following figureshows the process controlblock.

    Context Switch:

    1. When CPU switches to another process,the system must save the state of the oldprocess and loadthe savestate for the new process.

    2. Context-switch timeis overhead;the system does no useful work while switching.

    3. Time dependent on hardware support

    Cooperating Processes & Independent Processes

    Independent process:one that is independentof the rest of the universe.

    x Itsstate is not shared in any way by any other process.x Deterministic:inputstate alonedeterminesresults.x Reproducible.x Can stop and restart with no bad effects (only timevaries). Example:program that sums the

    integersfrom 1 to i (input).

    There are many differentways in which a collection of independentprocesses mightbe executed on a processo

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    33/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 33

    x programming:a singleprocess is run to completionbefore anythingelsecan be runon the processor.

    x Multiprogramming:share one processor among several processes.If no shared state,x U

    then order of dispatchingis irrelevant.n

    ix Multiprocessing:if multiprogrammingworks, then it shouldalsobe ok to runp processes in parallel on separate processors.r

    . o Ao givenprocess runs on only one processor at a time.

    . o Ag process may run on differentprocessors at differenttimes(move state,assume

    processors rare identical).

    . o Caannot distinguishmultiprocessingfrom multiprogrammingon a very fine grain.m

    Cooperatinmg processes:

    ix Machninemust modelthe social structures of the peoplethat use it.Peoplecooperate,so

    macghine

    mus:t support that cooperation.Cooperationmeans shared state,e.g. a singlefile system. xCooperatingprocesses are those that share state.(May or may not actually be "cooperating")xBehavioar is nondeterministic:depends on relative executionsequence and cannot be predicteda

    priori. x Behavior is irreproducible.x Example:one process writes "ABC", another writes"CBA".s Can get differentoutputs,cannot

    telliwhat comes from which. E.g. which process output first "C" in "ABCCBA"? Note thesubntlestate sharingthat occurs here via the terminal. Notjustanythingcan happen,though.Forgexample, "AABBCC" cannot occur.

    le

    1. Independentprocess cannot affect or be affected by the executionof another process2. Cooperaptingprocess can affect or be affected by the executionof another process

    r 3. Advantages of process cooperationoc x Informationsharinge x Computationspeed-ups x Modularitys x Convenience

    x is

    run

    t oU

    n

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    34/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 34

    2.4 INTERPROCESS COMMUNICATION (IPC)

    1. Mechanism for processes to communicateand to synchronize theiractions.2. Message system processes communicatewith each other withoutresortingto shared variables3. IPC facility providestwo operations:send(message) message size fixed or variablereceive(message)4. If P and Q wish to communicate,they need to:exchangemessages via send/receive5. Implementationof communicationlink

    physical (e.g., shared memory, hardware bus)logical (e.g., logical properties)

    Communications Models

    there are two types of communicationmodels

    1. Multi programming2. Shared Memory

    Direct Communication

    1. Processes must name each other explicitly:

    x send (P, message) send a message to process P x receive(Q, message) receive a message from process Q

    2. Propertiesof communicationlink

    x Linksare establishedautomatically x A link is associatedwith exactly one pair of

    communicatingprocesses xB

    etweeneach pairthere exists exactly one link x The link may beunidirectional, but is usually bi-directional

    Indirect Communication

    1. Messages are directedand receivedfrom mailboxes (also referred to as ports)

    x Each mailbox has a uniqueid

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    35/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 35

    x Processes can communicateonly if they share a mailbox

    2. Propertiesof communicationlink

    x Link establishedonly if processes share a common mailbox

    x A link may be associatedwith many processes

    x Each pairof processes may share several communicationlinks x Link may be unidirectionalor bi-directional

    3. Operations

    . o create a new mailbox

    . o send and receive messages through mailbox

    . o destroy a mailbox

    4.Primitives are definedas:send(A, message) send a message to mailbox A receive(A, message) receive a

    message from mailbox A

    5.Mailbox sharingP1, P2, andP3 share mailbox A P1, sends;P2 andP3 receive Who gets the message?

    6. Solutions Allow a link to be associatedwith at most two processes

    Allow only one process at a timeto execute a receive operationAllow the system to select

    arbitrarily the receiver. Sender is notifiedwho the receiver was.

    Synchronization

    1. Message passingmay be eitherblocking or non-blocking2. Blocking is consideredsynchronous

    ->Blocking send has the sender block until the message is received. ->Blocking receive has the receiver blockuntil a message is available.

    3. Non-blockingis consideredasynchronous->Non-blockingsend has the sender send the message and continue.->Non-blocking receive has the receiver receive a valid message or null.

    Buffering

    ->Queue of messages attached to the link; implemented in one of three ways

    1. Zero capacity 0 messages sender must wait for receiver (rendezvous)

    2. Boundedcapacity finite lengthof n messages Sender must wait if link full

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    36/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 36

    3. Unbounded capacity infinite lengthsender never waits

    2.5 MULTI THREADED PROGRAMMING

    Despiteof the fact that a thread must execute in process, the process and its associatedthreads are differentconcept.Processes are used to group resources together and threads are the entitiesscheduledfor executionon the CPU. A thread is a single sequence stream within in a process. Because threads have some of thepropertiesof processes,they are sometimescalled lightweight processes. In a process,threads allow multipleexecutionsof streams.In many respect,threads are popularway to improveapplicationthrough parallelism.The CPU switches rapidly back and forth among the threads giving illusion that the threads are running inparallel. Like a traditional process i.e., process with one thread, a thread can be in any of several states(Running, Blocked, Ready or Terminated). Each thread has its own stack. Since thread will generally calldifferent procedures andthus adifferent execution history. This is why thread needs its ownstack. Anoperatingsystem that has thread facility,the basic unitof CPU utilization is a thread.A thread has or consistsof a program counter (PC), a registerset,and a stack space.Threadsare not independentof one other likeprocesses as a result threads shares with other threads their code section, data section, OS resources alsoknown as task, such as open files and signals.

    Processes Vs Threads

    As we mentionedearlier that in many respect threads operate in the same way as that of processes.Some ofthe similarities and differencesare:

    Similarities

    x Likeprocesses threads share CPU and only one thread active (running) at a time.x Likeprocesses,threads within a processes,threads within a processes execute sequentially.x Likeprocesses,thread can create children.x And like process,if one thread is blocked, another thread can run.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    37/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 37

    Differences

    x Unlike processes,threads are not independentof one another.x Unlike processes,all threads can access every address in the task .x Unlike processes,thread are designto assistone other.Note that processes mightor mightnot

    assistone another because processes may originatefrom differentusers.

    Why Threads?

    Following are some reasons why we use threads in designingoperatingsystems.

    1. A process with multiple threads make a great server for exampleprinterserver.2. Becausethreads can share common data,they do not need to use interprocesscommunication.3. Becauseof the very nature,threads can take advantage of multiprocessors.4. Responsiveness

    5. Resource Sharing6. Economy7. Utilization of MP Architectures

    Threadsare cheap in the sense that

    1. They only need a stack and storage for registerstherefore,threads are cheap to create.2. Threadsuse very little resources of an operatingsystem in which they are working. That is, threads do not

    need new address space,globaldata,program code or operatingsystem resources.3. Context switching are fast when working with threads.The reason is that we only have to save and/or

    restore PC, SP and registers.

    But thischeapness does not come free -the biggestdrawback is that there is no protectionbetween threads.

    Single and Multithreaded Processes

    User-Level Threads

    1. Threadmanagement done by user-level threads library

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    38/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 38

    Three primary thread libraries:-> POSIX Pthreads-> Win32 threads

    -> Java threads

    User-level threads implement in user-level libraries, rather than via systems calls, so thread switching doesnot need to call operatingsystem and to cause interruptto the kernel. In fact, the kernel knows nothingaboutuser-level threads and manages them as if they were single-threadedprocesses.

    Advantages:

    The most obviousadvantage of thistechniqueis that a user-level threads package can be implementedon anOperatingSystem that does not support threads.Some other advantages are

    x User-level threads does not requiremodification to operatingsystems. x Simplerepresentation:Each thread is represented simply by a PC, registers,stack and a smallcontrolblock, all stored in the user process address space.x Simple Management:Thissimply means that creatinga thread,switching between threads and synchronizationbetween threads can all be done withoutinterventionof the kernel. x Fast and Efficient:Threadswitching is not much more expensive than a procedure call.

    Disadvantages:

    x There is a lack of coordination between threads and operating system kernel. Therefore, process aswhole gets one timeslice irrespectof whether process has one thread or 1000 threads within. Itis up

    to each thread to relinquish controlto other threads.x User-level threads requires non-blocking systems call i.e., a multithreaded kernel. Otherwise, entire

    process will blockedin the kernel, even if there are runablethreads left in the processes.For example,if one thread causes a page fault, the process blocks.

    Kernel-Level Threads

    1. Supported by the Kernel

    Examples:->WindowsXP/2000,->Solaris , ->Linux,->Tru64UNIX, ->Mac OS X

    In thismethod,the kernel knows about and manages the threads.No runtimesystem is needed in thiscase.Insteadof thread table in each process, the kernel has a thread table that keeps track of all threads in thesystem. In addition, the kernelalsomaintains the traditional process table to keep track of processes.OperatingSystems kernel providessystem call to create and manage threads.

    Advantages:

    x Becausekernel has full knowledgeof all threads,Schedulermay decideto give more timeto aprocess having largenumber of threads than process having small number of threads.x

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    39/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 39

    Kernel-levelthreads are especially good for applicationsthat frequently block.

    Disadvantages:

    xThe kernel-level threads are slow and inefficient. For instance,threads operationsare hundreds of timesslower than that of user-level threads.

    x Since kernel must manage and schedule threads as well as processes. It requirea full thread controlblock (TCB) for each thread to maintain informationabout threads. As a result there is significantoverhead and increasedin kernel complexity.

    Advantages of Threads over Multiple Processes

    x Context Switching Threadsare very inexpensive to create and destroy,and they are inexpensive torepresent.For example, they requirespace to store,the PC, the SP, and the general-purposeregisters,butthey donot require space to share memory information, Information about open files of I/Odevices in use,etc.With so little context,it is much faster to switch between threads.In other words,it is relatively easierfor a context switch usingthreads.

    x Sharing Treads allow the sharingof a lot resources that cannot be shared in process, for example,sharingcode section,data section,OperatingSystem resources like open file etc.

    Disadvantages of Threads over Multiprocesses

    x Blocking The majordisadvantageif that if the kernel is single threaded,a system call of one thread willblock the whole process and CPU may be idle duringthe blocking period.

    x Security Since there is, an extensive sharingamong threads there is a potentialproblemof security. Itisquite possible that onethread overwrites the stack of another thread (ordamaged shared data)althoughit is very unlikely since threads are meant to cooperate on a single task.

    Application that Benefits from Threads

    A proxy server satisfying the requests for a number of computers on a LAN would be benefitedby a multi-threaded process. In general, any program that has to do more than one task at a timecouldbenefit frommultitasking. For example, a program that reads input,process it,and outputs couldhave three threads,onefor each task.

    Application that cannot Benefit from Threads

    Any sequentialprocess that cannot be divided intoparallel task will not benefitfrom thread,as they wouldblock until the previousone completes.For example, a program that displays the timeof the day would notbenefitfrom multiple threads.

    2.6 OVERVIEW:MULTITHREADING MODELS

    Many-to-One One-to-One Many-to-Many

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    40/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 40

    Many-to-One Many user-level threads mapped to single kernel thread->Examples:->Solaris Green Threads, ->GNU PortableThreads

    One-to-One

    1. Each user-level thread maps to kernel thread

    ExamplesWindows NT/XP/2000 Linux Solaris 9 and later

    Many-to-Many Model

    1. Allows many user level threads to be mapped to many kernel threads.

    2. Allows the operatingsystem to create a sufficient number of kernel threads.3. Solaris priorto version 9.4. Windows NT/2000with the ThreadFiber package.

    2.7 THREAD LIBRARIES, THREADING ISSUES.

    Resources used in ThreadCreation and Process Creation

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    41/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 41

    When a new thread is created it shares its code section,data sectionand operatingsystem resources like openfiles with other threads.But it is allocatedits own stack, registerset and a program counter.

    The creationof a new process differs from that of a thread mainly in the fact that all the shared resources of athread are needed explicitly for each process.So though two processes may be runningthe same pieceof codethey need to have theirown copy of the code in the mainmemory to be ableto run. Two processes alsodo notshare other resources with each other.This makes the creationof a new process very costly compared to thatof a new thread.

    Thread Pools

    1. Create a number of threads in a poolwhere they await work

    thread

    Advantages:Usually slightly faster to service a request with an existing thread than create a new

    Allows the number of threads in the application(s) to be bound to the size of the pool

    Context Switch

    To give each process on a multiprogrammedmachinea fair share of the CPU, a hardware clock generatesinterruptsperiodically. This allows the operating system to scheduleall processes in main memory (using

    schedulingalgorithm)to run on the CPU at equal intervals. Each timea clock interruptoccurs, the interrupthandlerchecks how much time the current runningprocess has used. If it has used up its entire time slice,then the CPU schedulingalgorithm(in kernel) picks a differentprocess to run. Each switch of the CPU fromone process to another is called a context switch.

    Major Steps of Context Switching

    x The values of the CPU registersare saved in the process tableof the process that was runningjustbefore theclock interruptoccurred.x The registersare loadedfrom the process pickedby the CPU schedulerto run next.

    In a multiprogrammed uniprocessor computing system, context switches occur frequently enough that all

    processes appear to be runningconcurrently. If a process has more than one thread,the OperatingSystem canuse the context switching techniqueto schedulethe threads so they appear to execute in parallel. This is thecase if threads are implementedat the kernel level. Threadscan alsobe implementedentirely at the user levelin run-time libraries. Since in thiscase no thread scheduling is providedby the OperatingSystem, it is theresponsibility of the programmer to yield the CPU frequently enough in each thread so all threads in theprocess can make progress.

    Action of Kernel to Context Switch Among Threads

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    42/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 42

    The threads share a lot of resources with other peer threads belonging to the same process. So a contextswitch among threads for the same process is easy. Itinvolves switch of registerset,the program counter andthe stack. Itis relatively easy for the kernel to accomplishedthistask.

    Action of kernel to Context Switch Among Processes

    Context switches among processes are expensive. Before a process can be switchedits process controlblock(PCB) must be saved by the operatingsystem. The PCB consistsof the following information:

    x The process state.x The program counter,PC.x The values of the differentregisters.x The CPU schedulinginformationfor the process.x Memory management informationregardingthe process.x Possible accountinginformationfor thisprocess.x I/Ostatus informationof the process.

    When the PCB of the currently executingprocess is saved the operatingsystem loadsthe PCB of the nextprocess that has to be run on CPU. This is a heavy task and it takes a lotof time.

    2.8 PROCESS SCHEDULING: BASIC CONCEPTS

    The assignmentof physical processors to processes allows processors to accomplishwork. The problemofdeterminingwhen processors should be assignedand to which processes is called processor schedulingorCPU scheduling.When more than one process is runable,the operatingsystem must decidewhich one first.The part of the operatingsystem concerned with thisdecisionis called the scheduler,and algorithmit uses is

    called the schedulingalgorithm.

    CPUScheduler

    a. Selects from among the processes in memory that are ready to execute,and allocatesthe CPU to one ofthemb. CPU schedulingdecisionsmay take placewhen a process:

    1. Switches from runningto waiting state

    2. Switches from runningto ready state

    3. Switches from waiting to ready4. Terminates Scheduling under 1 and 4 is nonpreemptive All other schedulingispreemptive

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    43/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 43

    Dispatcher

    1. Dispatchermodulegives controlof the CPU to the process selectedby the short-term scheduler;this

    involves:

    switching context switching to user mode jumpingto the proper locationin the user program to restart that program

    2. Dispatch latency timeit takes for the dispatcherto stop one process and start another running.

    2.9 SCHEDULING CRITERIA

    1. CPU utilization keep the CPU as busy as possible2. Throughput# of processes that completetheirexecutionper timeunit

    3. Turnaroundtimeamount of timeto execute a particular process4. Waiting timeamount of timea process has been waiting in the ready queue5. Response timeamount of timeit takes from when a request was submitteduntil the first response is

    produced,not output (for time-sharingenvironment)

    General Goals

    Fairness

    Fairness is importantunder all circumstances. A schedulermakes sure that each process gets its fairshare of the CPU and no process can suffer indefinite postponement.Note that giving equivalentor equaltimeis not fair. Think ofsafety control andpayroll at a nuclearplant.

    Policy Enforcement

    The schedulerhas to make sure that system's policy is enforced.For example, if the local policy is safetythen thesafety control processes must be ableto run whenever they want to,even if it means delay inpayrollprocesses.

    Efficiency

    Schedulershouldkeep the system (or in particular CPU) busy cent percent of the timewhen possible.If the CPU and all the Input/Outputdevices can be kept runningall the time, more work gets done persecond than if some components are idle.

    Response TimeA schedulershouldminimize the response timefor interactive user.

    Turnaround

    A schedulershouldminimize the timebatch users must wait for an output.

    Throughput

    A schedulershouldmaximize the number ofjobsprocessed per unittime.A little thought will show that some of these goalsare contradictory.Itcan be shown that any scheduling

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    44/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 44

    algorithmthat favors some class ofjobshurts another class ofjobs. The amount of CPU timeavailable isfinite, after all.

    Preemptive Vs Nonpreemptive Scheduling

    The Scheduling algorithmscan be divided into two categories with respect to how they deal with clockinterrupts.

    Nonpreemptive Scheduling

    A schedulingdiscipline is nonpreemptiveif, once a process has been given the CPU, the CPU cannot betaken away from that process.

    Following are some characteristics of nonpreemptivescheduling

    1. In nonpreemptivesystem, shortjobsare made to wait by longerjobsbut the overall treatment of all

    processes is fair.2. In nonpreemptivesystem, response timesare more predictablebecause incominghighpriorityjobscan not

    displacewaitingjobs.3. In nonpreemptivescheduling,a schedularexecutesjobsin the following two situations.

    a. When a process switches from runningstate to the waiting state.b. When a process terminates.

    Preemptive Scheduling

    A schedulingdiscipline is preemptiveif, once a process has been given the CPU can taken away.

    The strategy of allowing processes that are logically runable to be temporarily suspended is calledPreemptiveScheduling and it is contrast to the "run to completion"method.

    2.10 SCHEDULING ALGORITHMS

    CPU Scheduling deals with the problem of decidingwhich of the processes in the ready queue is to beallocatedthe CPU. Following are some schedulingalgorithmswe will study.

    FCFS Scheduling. Round Robin Scheduling. SJF Scheduling. SRT Scheduling. Priority Scheduling. Multilevel Queue Scheduling. Multilevel Feedback Queue Scheduling.

    First-Come-First-Served (FCFS) Scheduling

    Other names of thisalgorithmare:x First-In-First-Out(FIFO)x Run-to-Completion

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    45/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 45

    x Run-Until-Done

    Perhaps, First-Come-First-Served algorithm is the simplest schedulingalgorithm is the simplest schedulingalgorithm.Processes are dispatchedaccordingto theirarrival timeon the ready queue.Being a nonpreemptivediscipline, once a process has a CPU, it runs to completion.The FCFS schedulingis fair in the formal senseor human sense of fairness but it is unfair in the sense that longjobsmake shortjobswait and unimportantjobsmake importantjobswait.

    FCFS is more predictable than most of other schemes since it offers time. FCFS scheme is not useful inschedulinginteractive users because it cannot guarantee good response time. The code for FCFS schedulingissimple to write and understand.One of the majordrawback of thisscheme is that the average time is oftenquitelong. The First-Come-First-Served algorithm is rarely used as a master scheme in modern operatingsystems but it is often embedded within other schemes.

    Example:-ProcessBurstTime

    P1 24

    P2 3

    P3 3

    Suppose that the processes arrive in the order:P1 ,P2 ,P3 ,The Gantt Chart for the scheduleis:

    Waiting timeforP1 = 0;P2 = 24;P3 = 27, Average waiting time:(0 + 24 + 27)/3= 17 Suppose that the

    processes arrive in the orderP2 ,P3 ,P1 , The Gantt chart for the scheduleis:

    Waiting timeforP1 = 6; P2 =0;P3 = 3, Average waiting time:(6 + 0 + 3)/3= 3Round Robin Scheduling

    x One of the oldest,simplest, fairest and most widely used algorithmis round robin(RR). x Inthe round robinscheduling,processes are dispatchedin a FIFO manner but are given a limitedamount of CPU timecalled a time-slice or a quantum.

    x If a process does not completebefore its CPU-time expires, the CPU is preempted and given to the next

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    46/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 46

    process waiting in a queue.The preempted process is then placedat the back of the ready list.x Round Robin Scheduling is preemptive(at the end of time-slice) therefore it is effective in timesharing

    environmentsin which the system needs to guarantee reasonableresponse timesfor interactive users.

    x The only interestingissuewith round robinscheme is the lengthof the quantum.Settingthe quantumtoo short causes too many context switches and lower the CPU efficiency. On the other hand,settingthe quantum too longmay cause poor response timeand appoximatesFCFS.

    In any event,the average waiting timeunder round robinschedulingis often quitelong.

    1. Each process gets a small unitof CPU time(time quantum), usually 10-100 milliseconds. After thistimehas elapsed,the process is preempted and added to the end of the ready queue.

    2. If there are n processes in the ready queue and the timequantum is q, then each process gets 1/n of theCPU timein chunks of at most q timeunitsat once.No process waits more than (n-1)q timeunits.

    3. Performance ->q large. FIFO ->q small . q must be largewith respect to context switch, otherwiseoverhead is too high. Example:ProcessBurstTime

    P1 53P2 17P3 68P4 24

    The Gantt chart is: ->Typically, higheraverage turnaround than SJF, but better response

    P1 P2 P3 P4 P1 P3 P4 P1 P3 P3

    0 20 37 57 77 97 117 121 134 154 162

    Shortest-Job-First (SJF) Scheduling

    x Other name of thisalgorithmis Shortest-Process-Next (SPN).x Shortest-Job-First (SJF) is anon-preemptive disciplinein whichwaitingjob(orprocess) with the

    smallestestimatedrun-time-to-completionis run next. In other words, when CPU is available, it isassignedto the process that has smallestnext CPU burst.

    x TheSJF scheduling is especially appropriate forbatchjobsforwhich the run times areknown inadvance. Since the SJF scheduling algorithm gives the minimum average time for a given set ofprocesses,it is probably optimal.

    x The SJF algorithmfavors shortjobs(or processors) at the expense of longerones.xThe obviousproblemwith SJF scheme is that it requirespreciseknowledgeof howlongajobor process will run, and thisinformationis not usually available. x The bestSJF algorithmcan do is to rely on user estimatesof run times.

    In the production environment wherethe samejobsrunregularly, it may bepossible to provide

    reasonableestimateof run time, based on the past performance of the process.But in the developmentenvironmentusers rarely know how theirprogram will execute.

    Like FCFS, SJF is non preemptivetherefore,it is not useful in timesharingenvironmentin which reasonableresponse timemust be guaranteed.

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    47/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 47

    1 Associate with each process the lengthof its next CPU burst.Use these lengthsto scheduletheprocess with the shortest time2 Two schemes:

    x nonpreemptiveonce CPU given to the process it cannot be preempted until completesitsCPU burst

    x preemptiveif a new process arrives with CPU burst lengthless than remainingtimeofcurrent executingprocess,preempt.This scheme is know as the ShortestRemaining-Time-First (SRTF)

    3. SJF is optimalgives minimum average waiting timefor a given set of processes

    Process Arrival Time Burst Time

    P1 0.0 7

    P2 2.0 4

    P3 4.0 1

    P4 5.0 4

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    48/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 48

    -> SJF (preemptive)

    ->Average waiting time= (9 + 1 + 0 +2)/4= 3

    Shortest-Remaining-Time (SRT) Scheduling

    x The SRT is the preemtivecounterpart of SJF and useful in time-sharingenvironment.x In SRT scheduling,the process with the smallestestimatedrun-timeto completionis run next,

    including new arrivals.x In SJF scheme,once ajobbeginexecuting, it run to completion.x In SJF scheme,a runningprocess may be preempted by a new arrival process with shortest

    estimatedrun-time.x The algorithmSRT has higheroverhead than its counterpart SJF.x The SRT must keep track of the elapsedtimeof the runningprocess and must handleoccasional

    preemptions.x In thisscheme,arrival of small processes will run almostimmediately. However, longerjobshave even longermean waiting time.

    Priority Scheduling

    x A priority number (integer) is associatedwith each processx The CPU is allocatedto the process with the highestpriority (smallest integer{ highestpriority)

    o ->Preemptiveo ->nonpreemptive

    x SJF is a priority schedulingwhere priority is the predictednext CPU burst timex Problem{ Starvation low priority processes may never execute

    x Solution{

    Aging as timeprogresses increasethe priority of the process

    The basic idea is straightforward:each process is assigneda priority, and priority is allowed to run. Equal-Priority processes are scheduled in FCFS order. The shortest-Job-First (SJF) algorithm is a special case ofgeneralpriority schedulingalgorithm.An SJF algorithmis simply a priority algorithmwhere the priority isthe inverse of the (predicted)next CPU burst.That is, the longerthe CPU burst,the lower the priority andvice versa.

    Priority canbe defined either internally orexternally. Internally defined priorities usesome measurablequantitiesor qualities to compute priority of a process.

    Examplesof Internalpriorities are

  • 7/27/2019 Cse v Operating Systems [10cs53] Notes

    49/150

    Operating Systems 10CS53

    CITSTUDENTS.IN 49

    x Time limits. x Memory requirements.x File requirements,for example, number of open files. x CPU Vs I/Orequirements.

    Externally definedpriorities are set by criteria that are externalto operatingsystem such as

    x The importanceof p