THE HONG KONG POLYTECHNIC UNIVERSITY Department of Electronic and Information Engineering EIE 272 CAOS Operating Systems Part II Processes, PCB, Context Switch Instructor Dr. M. Sakalli enmsaka@eie.polyu.edu.hk EIE 272 1 Process and the terminology Process: : A set of instructions to be executed as a program, so it is a program. In some systems also called task. Each process has a descriptive information procedure to track the progress made. This is called as process control block. Jobs are called processes that start, do something and quit, like production line processes. EIE 272 M. Sakalli 2
Points of Discussion Memory Management Process Creation CPU Scheduling EIE 272 M. Sakalli 3 Memory allocated for the active processes. Program counter follows each instruction (addresses) for the referred jobs to be executed. EIE 272 M. Sakalli Source: Stallings Ch.3 4
Source: Stallings Ch.3 The simplest process model is in two states,, a process running or non-running. EIE 272 M. Sakalli 5 Process A Process B Process B Source: Stallings Ch.3 EIE 272 M. Sakalli 6
Process A Time out precludes any single process from monopolizing the resources. Process A Process B Process C Process C EIE 272 M. Sakalli Source: Stallings 7 Ch.3 Process Running state Process non-running state but made ready in queue Two state process model flow diagram Source: Stallings Ch.3 EIE 272 M. Sakalli 8
Process Creation: To create a process OS needs these three components 1. An executable program 2. Data 3. Context information All information the operating system needs to interleave and restart a process. When OS receives a request to create a process, it builds the data structures and allocates a space for this process in memory. EIE 272 M. Sakalli 9 Process Creation: Demand for a process In a batch environment, request for a job activates the OS to create a process. In an interactive environment, when a user logs on the system, a new process is initiated. Operating system can also create a process on behalf of an application,, i.e. for an application requesting to print a file, so that the printing request can continue independently from the application. A process or a server (like socket) can request a new process for each client it handles (spawning). EIE 272 M. Sakalli 10
Process Creation: Parent-Child Hierarchy When OS initiates a process with the explicit request of another process, this is called as spawning, and the new process created is called child that will be dependent on the parent process. Similarly a child process can create its own child processes. The parent-child hierarchy is similar to a tree structure. Source sharing: : Child processes may be restricted to share the resources of the parents or OS can allocate extra space for the new child processes. Depends to the application and OS used. But very flexible. Anyone using the system must be already be running a shell or a command line interpreter to be able to talk to the system. The command interpreter is a process, to whom user asks to generate a new process. EIE 272 M. Sakalli 11 Process Hierarchy When a child is created, it may either duplicate its parent process or load a completely new program. And parent process may choose to execute along side of its child processes or wait for the child processes to finish their tasks before proceeding. If any parent is signaled or destroyed (killed), consecutive child processes are also signaled/destroyed. This is not supposed to be the case. A branch of child processes can be dispatched from the parent. When fork() is executed, it creates a child, returns 1 and PID to parent and 0 to child, but if unsuccessful, returns - 1.. and wait(). VMS and Unix do not allow orphan processes. In Unix, the wait() system call provides a mechanism for the parent to distinguish among its child processes. EIE 272 M. Sakalli 12
The way a process is terminated In a batch environment, a job should have a Halt instruction to indicate the end of the job with an interrupt to alert OS. In an interactive environment, a system call is activated when user closes the environment or the application. A number of fault of error conditions can lead to the termination of the process. A process can be terminated by its parent process or when its parent process terminates, child process will terminated. When a process completes its task, it is terminated internally or externally. EIE 272 M. Sakalli 13 Reasons for Process Termination Normal completion Time limit exceeded (might be requeued!) Memory unavailable Bounds violation Protection error example write to read-only file Arithmetic error Time overrun process waited longer than a specified maximum limit for an event to occur Source: Stallings Slights EIE 272 M. Sakalli 14
Reasons for Process Termination I/O failure Invalid instruction happens when try to execute data Privileged instruction Data misuse Operating system intervention such as when deadlock occurs Parent terminates so child processes terminate Parent requests for a termination child process Source: Stallings Slights EIE 272 M. Sakalli 15 Time-out interrupt I/O or Event completed Event wait or I/O Source: Stallings Ch.3 Modified 1. A process can be in only one state. 2. However many processes may be in a state such as in the waiting or in the blocked states 3. And only one process can be in the running state on any processor at a time. EIE 272 M. Sakalli 16
Five-State Process Model Two stage model does not include the cases where the processes are blocked or suspended. A more modularized approach have stages: 1. New state: : For a new process request, a. first the housekeeping cores are prepared, b. an identifier (PID) for the process is associated, c. and tables and memories are build. d. The program to be executed is stored in the secondary storage but not in the main memory yet, but the pointers are. EIE 272 M. Sakalli 17 Five-State Process Model 2. Exit state: Termination of the process moves the process to an exit state. a. Process execution can no longer proceed, b. Tables and other associated jobs are temporarily preserved somewhere by OS to give time for other auxiliary or support programs to extract extra information, i.e. accounting, billing, history, and performance utility programs. 3. Ready 4. Running 5. Blocked, suspended EIE 272 M. Sakalli 18
State transitions in Five-State Process Model: State-A [transition] State-B 1. Null [Request for a new Process] New 2. New state [Admit] Ready. If resources are available to accept a new process and if the maximum number of processes allowed at a time is not exceeded. 3. Ready [Dispatch] Running. If the given time for the current process in CPU is competed or if the process ends earlier, OS dispatches the next process in order. The priority based preemptive approach can be applied. Has it been applied? (OS( has preempted the application A, and dispatched B). B 4. Running [Release] Exit. If the task is completed or if it aborts earlier. EIE 272 M. Sakalli 19 State transitions: (cont d) State-A [transition] State-B 5. Running [Timeout] Ready. Re-queued if reaches to its maximum allowable time limit. 6. Running [Event-Wait] Blocked. If the running program requests something for which it must wait, it will be dislodged from the processor into blocked stage. The request may be to read from memory or disc, or may be coming out of another process. 7. Blocked [Event is complete] Ready. When the event for which it has been waiting occurs. 8. Ready [A A parent kills the process] Exit. A parent can kill the process or when a parent is terminated, all the child processes will be terminated. 9. Blocked [time-out] Exit. If the supplies for which the process has been waiting for can not be provided. EIE 272 M. Sakalli 20
Process admitted from job queue PCB-2 Process dispatch Process completed PCB-n FIFO I/O or Event completed PCB-1 I/O or Event to be completed PCB-q1 FIFO PCB-qn Child process to be executed STACK - So the queue buffer should be in LIFO? Queue diagram state and transitions. Abraham Silberschatz. Ch.4 Modified EIE 272 M. Sakalli 21 Process Control Block A process control block contains the information to enable successful ssful continuation of its execution. Each process have just one PCB and the content: a. Pointer for next PCB address. b. Process state. c. Process ID. d. Program counter indicating the address of the instruction to be fetched. e. CPU registers (stack, index reg,, general-purpose reg). f. CPU-scheduling info: : Process priority, pointers to scheduling queues. g. Memory management information: : Base and limit registers. h. Accounting Info: : The amount of CPU and real time used, time limits, account, job, process #. i. I/O status info: : List of I/O devices allocated, and list of files open. EIE 272 M. Sakalli 22
PCB enum state_type {new, ready, running, blocked, terminated}; typedef struct P_control_block { struct P_control_block *next_pcb; enum state_type state; int pid; address PC; int reg_file[numregs]; int priority; address page_table;... } control_block; Abraham Silberschatz. Ch.4 EIE 272 M. Sakalli 23 Dispatching From Process to Process Dispatcher Dispatcher Abraham Silberschatz. Ch.4 EIE 272 M. Sakalli 24
Process Blocked I/O interrupt Loading B Loading C Loading A Loading C Source: Stallings Ch.3 EIE 272 M. Sakalli 25 Switching between states of running and non- running: Context Switch. Information need to be recorded into PCB.. so that the continuity of the process can be provided smoothly with minimum amount of information being swapped in and out of memory. Writing and reading of this information in and out of the PCB and MMU and recovering it back its running state is called as context switching. It incurs a cost to the system to be minimized. Performed by dispatcher. Typical time 1µsec - 1 ms (Hardware dependent) EIE 272 M. Sakalli 26
Context Switch The information saved is called overhead: the values at the registrations, the status of all open files, present position in the program (PC), and contents of Memory Management Unit. The contents of (PCB) that are related to the conversion table of addresses must be downloaded into the MMU. That is the one reason why the context switching is an expensive procedure. EIE 272 M. Sakalli 27 Scheduling Queues [Queue Header : Queue] 1. Job queue: : Every newly created process enters this queue. 2. Ready queue: : Resides in main memory keeping the processes ready to enter to the running state. i. Every queue header have a pointer indicating the locations of the first and the last PCBs. ii. PCBs have a link structure: : a pointer indicating start of the next PCB in the queue. 3. Dedicated device queues,, when a process is interrupted or waits for an event to complete or a process to execute a job, process enters into block state. Device queue is to accommodate jobs or processes waiting in the blocked state for I/O queue. The queue structure is linked same as the ready queue. But remember in the case of consecutive processes, the queue strategy is LIFO. EIE 272 M. Sakalli 28
Abraham Silberschatz. Ch.4 Ready Queue & Various I/O Device Queues EIE 272 M. Sakalli 29 Process Schedulers A process migrates between various scheduling queues.. In batch systems there are more processes submitted than processes that can be executed immediately. These process are spooled into a queue. The long-term scheduler selects processes from the job queue into memory for ready queue. Slow runner. Controls the stability of multiprogramming. The average rate of process creation must be equal to the average departure rate. So it is invoked only when a process leaves the system that gives the time to work on which process should be chosen. The short term scheduler (or CPU scheduler), selects one of the processes in the ready queue to load into CPU. Need to scan the queue fast enough to locate the next process. The ready queue is supposed be FIFO, may be priority based, tree or simply unordered linked list. EIE 272 M. Sakalli 30
CPU bound process & I/O bound process Long-term scheduler determines which processes should be loaded into ready-queue.. If jobs loaded into ready queue invoke very frequent I/O requests, CPU will remain idle, this situation is called as I/O-bound bound-process.. However, if the jobs consume a lot of CPU cycles, CPU will be very busy (CPU( CPU- bound processes) ) to complete the computations (ready queue longer) while device queues will be nearly empty. So it is important that the long term scheduler select a good mixture of I/O-bound and CPU-bound processes. In some systems there is no long term scheduler For example time-sharing systems such as Unix do not have one. But relies on the physical limitations of the number of processes that can be run, or self adjusting nature of the users. Some OS introduces medium-term schedulers to reduce the degree of programming (swapping). EIE 272 M. Sakalli 31 Summing up features of schedulers Long term scheduler controls the # of processes in ready queue (main memory).. So that.. For stability of multiprogramming in terms of the balance between CPU-bound (CPU intensive) and I/O-bound processes (I/O intensive). 1. CPU burst: : A period of uninterrupted CPU activity. 2. I/O burst. Slow.. Short term scheduler particularly important for timesharing (interactive) processing: To schedule the jobs in ready-to-run state. Runs very frequently (~every few milliseconds). Must be quick/small particularly for timesharing. EIE 272 M. Sakalli 32
Non-preemptive and preemptive CPU scheduling III. Non-preemptive Scheduling: : Process doesn t t release the CPU until the process is completed or an I/O request transferring the process into the waiting (blocked) state. If cooperative,, process relinquishes the CPU control herself to the other jobs. Preemptive: : If a high-priority task becomes ready for execution it can immediately preempt the execution of a lower-priority task and acquire processor without having to wait for the next regular rescheduling. Non-preemptive one has a shorter header but might capture the CPU, so time distribution to the processes may be un-fair fair. Preemptive one can be fare, but it has longer overhead and it may cause system failures and it requires extra HW such as for timing, and an expensive due to the context switching. Politely preemptive: : Time is shared, but if a task is in its critical section, system will not interrupt this job until critical section is executed. Unix and Windows NT works like this. EIE 272 M. Sakalli 33 Dispatcher Dispatcher module gives control of the CPU to the process selected by the short-term term scheduler; this involves: 1. Context switching 2. Switching to user mode 3. Jumping to the next job location after determining the next job in the ready queue. Dispatch latency time it takes for the dispatcher to stop one process and start another running. EIE 272 M. Sakalli 34
Scheduling Metrics CPU utilization (in %) Throughput The # of Processes completed per unit time Turnaround time From the time of submission to the completion Waiting time Time in ready queue Response time Interactive systems EIE 272 M. Sakalli 35 Algorithms First-Come, First-Served Shortest-Job Job-First Priority Round-Robin Robin Multilevel Queue Multilevel Feedback Queue Algorithm Evaluation EIE 272 M. Sakalli 36