Module 2
Module 2
MODULE 2
Page 1 of 60
Operating System 22CSE44
PROCESS MANAGEMENT
PROCESS CONCEPT
• Its current activity is indicated by PC (Program Counter) and the contents of the
processor's registers.
The Process
Process memory is divided into four sections as shown in the figure below:
• The stack is used to store temporary data such as local variables, function parameters,
function return values, return address etc.
• The heap which is memory that is dynamically allocated during process run time
• Note that, there is a free space between the stack and the heap. When the stack is full,
it grows downwards and when the heap is full, it grows upwards.
Page 2 of 60
Operating System 22CSE44
Q)Illustrate with a neat sketch, the process states and process control block.
Process State
A Process has 5 states. Each process may be in one of the following states –
[Link] - The process has all the resources it needs to run. It is waiting to be assigned to the
processor.
[Link] - The process is waiting for some event to occur. For example, the process may be
waiting for keyboard input, disk access request, inter-process messages, a timer to go off, or
a child process to finish.
Page 3 of 60
Operating System 22CSE44
• Process State – The state of the process may be new, ready, running, waiting, and
so on.
• Program counter – The counter indicates the address of the next instruction to
be executed forthis process.
• CPU registers - The registers vary in number and type, depending on the
computer architecture. They include accumulators, index registers, stack pointers,
and general-purpose registers. Along with the program counter, this state
information must be saved when an interrupt occurs, to allow the process to be
continued correctly afterward.
• CPU scheduling information- This information includes a process priority,
pointers to scheduling queues, and any other scheduling parameters.
• Memory-management information – This includes information such as the
value of the base and limit registers, the page tables, or the segment tables.
• Accounting information – This information includes the amount of CPU and real
time used, time limits, account numbers, job or process numbers, and so on.
• I/O status information – This information includes the list of I/O devices
allocated to the process, a list of open files, and so on.
The PCB simply serves as the repository for any information that may vary from process
to process.
Page 4 of 60
Operating System 22CSE44
Page 5 of 60
Operating System 22CSE44
Process Scheduling
Scheduling Queues
• As processes enter the system, they are put into a job queue, which consists of all
processes inthe system.
• The processes that are residing in main memory and are ready and waiting to
execute are kepton a list called the ready queue. This queue is generally stored as
a linked list.
• A ready-queue header contains pointers to the first and final PCBs in the list.
Each PCBincludes a pointer field that points to the next PCB in the ready queue.
Page 6 of 60
Operating System 22CSE44
Page 7 of 60
Operating System 22CSE44
SCHEDULERS
Schedulers are software which selects an available program to be assigned to CPU.
• A long-term scheduler or Job scheduler – selects jobs from the job pool
(of secondarymemory, disk) and loads them into the memory.
If more processes are submitted, than that can be executed immediately, such
processes will bein secondary memory. It runs infrequently, and can take time to
select the next process.
• The short-term scheduler, or CPU Scheduler – selects job from memory and
assigns theCPU to it. It must select the new process for CPU frequently.
• The medium-term scheduler - selects the process in ready queue and
reintroduced into thememory.
An efficient scheduling system will select a good mix of CPU-bound processes and
I/O bound
processes.
• If the scheduler selects more I/O bound process, then I/O queue will be
full and readyqueue will be empty.
• If the scheduler selects more CPU bound process, then ready queue will be
full and I/Oqueue will be empty.
Time sharing systems employ a medium-term scheduler. It swaps out the process
from ready queue and swap in the process to ready queue. When system loads get
Page 8 of 60
Operating System 22CSE44
high, this scheduler will swap one or more processes out of the ready queue for a
few seconds, in order to allow smaller faster jobs to finish up quickly and clear the
system.
Context switching
• The task of switching a CPU from one process to another process is called context
switching. Context-switch times are highly dependent on hardware support
(Number of CPU registers).
• Whenever an interrupt occurs (hardware or software interrupt), the state of the
currentlyrunning process is saved into the PCB and the state of another process is
restored from the PCBto the CPU.
• Context switch time is an overhead, as the system does not do useful work while
switching.
Page 9 of 60
Operating System 22CSE44
OPERATIONS ON PROCESSES
managing memory and file systems. The init process with a PID of 1, serves
as a parent process for all user processes.
A process will need certain resources (CPU time, memory, files, I/O devices) to
accomplish its task. When a process creates a subprocess, the subprocess may be
Page 10 of 60
Operating System 22CSE44
There are two options for the parent process after creating the child:
• Wait for the child process to terminate and then continue execution. The parent
makes a wait()system call.
• Run concurrently with the child, continuing to execute without waiting.
Two possibilities for the address space of the child relative to the parent:
• The child may be an exact duplicate of the parent, sharing the same program
and data segments in memory. Each will have their own PCB, including
program counter, registers, and PID. This is the behaviour of the fork system
call in UNIX.
• The child process may have a new program loaded into its address space,
with all new code and data segments. This is the behaviour of the spawn
system calls in Windows.
In UNIX OS, a child process can be created by fork() system call. The fork system
call, if successful, returns the PID of the child process to its parents and returns a
zero to the child process. If failure, it returns -1 to the parent. Process IDs of current
process or its direct parent can be accessed using the getpid( ) and getppid( )
system calls respectively.
Page 11 of 60
Operating System 22CSE44
The parent waits for the child process to complete with the wait() system call.
When the childprocess completes, the parent process resumes and completes its
execution.
In windows the child process is created using the function createprocess( ). The
createprocess( )returns 1, if the child is created and returns 0, if the child is not created.
Page 12 of 60
Operating System 22CSE44
Process Termination
• A process terminates when it finishes executing its last statement and asks the
operating systemto delete it, by using the exit () system call. All of the resources
assigned to the process like memory, open files, and I/O buffers, are deallocated
by the operating system.
• A process can cause the termination of another process by using appropriate
system call. The parent process can terminate its child processes by knowing of
the PID of the child.
• A parent may terminate the execution of children for a variety of reasons, such as:
The child has exceeded its usage of the resources, it has been allocated.
The task assigned to the child is no longer required.
The parent is exiting, and the operating system terminates all the children.
This is called cascading termination.
INTERPROCESS COMMUNICATION
• Information Sharing - There may be several processes which need to access the
same file. Sothe information must be accessible at the same time to all users.
Page 13 of 60
Operating System 22CSE44
Page 14 of 60
Operating System 22CSE44
2. Useful for sending large block of data Useful for sending small data.
System call is used only to create System call is used during every
3.
shared memory read and write operation.
Message is sent faster, as there are no
4. Message is communicated slowly.
system calls
• Shared Memory is faster once it is set up, because no system calls are required
and access occurs at normal memory speeds. Shared memory is generally
preferable when large amounts of information must be shared quickly on the
same computer.
• Message Passing requires system calls for every message transfer, and is
therefore slower, but it is simpler to set up and works well across multiple
computers. Message passing is generally preferable when the amount and/or
frequency of data transfers is small.
Shared-Memory Systems
• A region of shared-memory is created within the address space of a process, which
needs to communicate. Other process that needs to communicate uses this shared
memory.
• The form of data and position of creating shared memory area is decided by the
process. Generally, a few messages must be passed back and forth between the
cooperating processes first in order to set up and coordinate the shared memory
access.
• The process should take care that the two processes will not write the data to the
shared memory at the same time.
• This is a classic example, in which one process is producing data and another process
is consuming the data.
• The data is passed via an intermediary buffer (shared memory). The producer puts
Page 15 of 60
Operating System 22CSE44
the data to the buffer and the consumer takes out the data from the buffer. A
producer can produce one item while the consumer is consuming another item. The
producer and consumer must be synchronized, so that the consumer does not try to
consume an item that has not yet been produced. In this situation, the consumer
must wait until an item is produced.
• There are two types of buffers into which information can be put –
• Unbounded buffer
• Bounded buffer
• With Unbounded buffer, there is no limit on the size of the buffer, and so
on the dataproduced by producer. But the consumer may have to wait for
new items.
• With bounded-buffer – As the buffer size is fixed. The producer has to wait if
the buffer isfull and the consumer has to wait if the buffer is empty.
This example uses shared memory as a circular queue. The in and out are two
pointers to the [Link] in the code below that only the producer changes "in", and
only the consumer changes "out". First the following data is set up in the shared
memory area.
Page 16 of 60
Operating System 22CSE44
Message-Passing Systems
A mechanism to allow process communication without sharing address space. It is used
in distributedsystems.
• Message passing systems uses system calls for "send message" and "receive message".
• A communication link must be established between the cooperating processes
before messagescan be sent.
• There are three methods of creating the link between the sender and the receiver-
Page 17 of 60
Operating System 22CSE44
1. Naming
Processes that want to communicate must have a way to refer to each other. They can use
either director indirect communication.
a) Direct communication the sender and receiver must explicitly know each other’s
name. The syntaxfor send() and receive() functions are as follows-
• send (P, message) – send a message to process P
• receive(Q, message) – receive a message from process Q
Properties of communication link:
A mailbox or port is used to send and receive messages. Mailbox is an object into which
messagescan be sent and received. It has a unique ID. Using this identifier messages are
sent and received.
Two processes can communicate only if they have a shared mailbox. The send and receive
functionsare –
• send (A, message) – send a message to mailbox A
• receive (A, message) – receive a message from mailbox A
Properties of communication link:
• A link is established between a pair of processes only if they have a shared mailbox
Blocking (synchronous) send - sending process is blocked (waits) until the message is
received by receiving process or the mailbox.
Non-blocking (asynchronous) send - sends the message and continues (does not wait)
Page 19 of 60
Operating System 22CSE44
3. Buffering
When messages are passed, a temporary queue is created. Such queue can be of three
capacities:
Zero capacity – The buffer size is zero (buffer does not exist). Messages are not stored
inthe queue. The senders must block until receivers accept the messages.
Bounded capacity- The queue is of fixed size(n). Senders must block if the queue is full.
After sending ‘n’ bytes the sender is blocked.
Unbounded capacity - The queue is of infinite capacity. The sender never blocks.
Page 20 of 60
Operating System 22CSE44
MULTITHREADED PROGRAMMING
▪ thread ID
▪ PC
▪ register-set and
▪ stack.
• It shares with other threads belonging to the same process its code-section &data-
section.
• A traditional (or heavy weight) process has a single thread ofcontrol.
• If a process has multiple threads of control, it can perform more than one task at a
[Link] a process is called multithreaded process
Page 21 of 60
Operating System 22CSE44
MULTITHREADING MODELS
• Support for threads may be provided ateither
1. The user level, for user threads or
2. By the kernel, for kernel threads.
Many-to-One Model
Page 23 of 60
Operating System 22CSE44
One-to-One Model
Page 24 of 60
Operating System 22CSE44
Many-to-Many Model
Advantages:
Page 25 of 60
Operating System 22CSE44
THREAD LIBRARIES
• It provides the programmer with an API for the creation and management
ofthreads.
• Two ways of implementation:
1. First Approach:
Provides a library entirely in user space with no kernel support. All code and
data structuresfor the library exist in the user space.
2. SecondApproach
Provides a library entirely in user space with no kernel support. All code and
data structuresfor the library exist in the user space.
Three main threadlibraries:
1. POSIXP threads
2. Win32 and
3. Java.
Pthreads
Page 26 of 60
Operating System 22CSE44
Page 27 of 60
Operating System 22CSE44
Win32 threads
Java Threads
• The API provides a rich set of features for the creation and management of threads.
All Java programs comprise at least a single thread ofcontrol.
Page 28 of 60
Operating System 22CSE44
THREADING ISSUES
fork() and exec() System-calls
2. Other systems duplicate only the thread that invoked the forkO.
1. Synchronoussignals
1. A Default SignalHandler
2. A User-defined SignalHandler
Page 30 of 60
Operating System 22CSE44
THREAD POOLS
• Procedure:
1. When a server receives a request, it awakens a thread from the pool.
2. If any thread is available, the request is passed to it for service.
3. Once the service is completed, the thread returns to the pool.
• Advantages:
Servicing a request with an existing thread is usually faster
than waiting tocreate a thread.
The pool limits the no. of threads that exist at any one point.
Page 31 of 60
Operating System 22CSE44
SCHEDULER ACTIVATIONS
Page 32 of 60
Operating System 22CSE44
PROCESS SCHEDULING
Basic Concepts
• In a single-processor system,
▪ Only one process may run at a time.
▪ Other processes must wait until the CPU is rescheduled.
• Objective ofmultiprogramming:
▪ To have some process running at all times, in order to maximize
CPUutilization.
Page 33 of 60
Operating System 22CSE44
Page 34 of 60
Operating System 22CSE44
CPU SCHEDULER
• This scheduler
• selects a waiting-process from the ready-queue and
• allocates CPU to the waiting-process.
• The ready-queue could be a FIFO, priority queue, tree and list.
• The records in the queues are generally process control blocks (PCBs) of the
processes.
CPU Scheduling
Four situations under which CPU scheduling decisions take place:
1. When a process switches from the running state to the waiting state. For ex; I/O
request.
2. When a process switches from the running state to the ready state. For ex:
when an interrupt occurs.
3. When a process switches from the waiting state to the ready state. For ex:
completion of I/O.
4. When a process terminates.
Scheduling under 1 and 4 is non- preemptive. Scheduling under 2 and 3 is preemptive.
Once the CPU has been allocated to a process, the process keeps the CPU until it
releases the CPU either by terminating or by switching to the waiting state.
Preemptive Scheduling
This is driven by the idea of prioritized computation. Processes that are runnable may be
temporarily suspended
Disadvantages:
Page 35 of 60
Operating System 22CSE44
Dispatcher
SCHEDULING CRITERIA:
Page 36 of 60
Operating System 22CSE44
SCHEDULING ALGORITHMS
CPU scheduling deals with the problem of deciding which of the processes in
the ready-queue is to be allocated theCPU.
Following are some schedulingalgorithms:
FCFS Scheduling
• The process that requests the CPU first is allocated the CPUfirst.
• The implementation is easily done using a FIFOqueue.
• Procedure:
• Disadvantages:
1. Convoy effect: All other processes wait for one big process to get off
theCPU.
2. Non-preemptive (a process keeps the CPU until it releasesit).
3. Not good for time-sharingsystems.
4. The average waiting time is generally notminimal.
Page 38 of 60
Operating System 22CSE44
• Example: Suppose that the processes arrive in the order P1, P2,P3.
SJF Scheduling
• The CPU is assigned to the process that has the smallest next CPUburst.
• If two processes have the same length CPU burst, FCFS scheduling is
used to breakthetie.
Page 39 of 60
Operating System 22CSE44
because there isno way to know the length of the next CPUburst
• Advantage:
If the new process has a shorter next CPU burst than what
is left of the executing process, that process is preempted. It
is also known as SRTF scheduling (Shortest-Remaining-
Time-First).
Page 40 of 60
Operating System 22CSE44
preemptive SJF/SRTF: Consider the following set of processes, with the length
Priority Scheduling
process.
For example: time limits, memory requirements, no. f open files.
[Link]-defined priorities.
Set by criteria that are external to the OS
Forexample: importance of the process, political factors
Priority scheduling can be either preemptive or non-
preemptive.
[Link]
The CPU is preempted if the priority of the newly arrived process ishigher
than the priority of the currently running process.
[Link] Preemptive
The new process is put at the head of the ready-queue
Disadvantage: Indefinite blocking, where low-priority processes are left waiting indefinitely
for CPU.
Solution: Aging is a technique of increasing priority of processes that wait in system for a
long time.
Page 42 of 60
Operating System 22CSE44
• CPUscheduler
1. Picks the first process from theready-queue.
2. Sets a timer to interrupt after 1 time quantumand
3. Dispatches theprocess.
Page 43 of 60
Operating System 22CSE44
• Disadvantage:
Better response time than SJF.
Example: Consider the following set of processes that arrive at time 0, with
thelength of the CPU-burst time given inmilliseconds.
• Useful for situations in which processes are easily classified into different
groups.
Page 46 of 60
Operating System 22CSE44
A process may move between queues. The basic idea: Separate processes according to the
features of their CPU bursts. Forexample
[Link] a process uses too much CPU time, it will be moved to a lower-priority queue. This
scheme leaves I/O-bound and interactive processes in the higher-priority queues.
[Link] a process waits too long in a lower-priority queue, it may be moved to a higher-
priority queue This form of aging prevents starvation.
Page 47 of 60
Operating System 22CSE44
Symmetric Multiprocessing
The basic idea is:
Each processor is self-scheduling.
To do scheduling, the scheduler for eachprocessor
Examines the ready-queue and
Selects a process to execute.
Page 48 of 60
Operating System 22CSE44
Restriction: We must ensure that two processors do not choose the same
process and thatprocesses are not lost from the queue.
Processor Affinity
• In SMP systems,
1. Migration of processes from one processor to another are avoided and
2. Instead processes are kept running on same processor.
This is known asprocessor affinity.
• Two forms:
1. SoftAffinity
Load Balancing
Page 49 of 60
Operating System 22CSE44
2. PullMigration
An idle processor pulls a waiting task from a busy processor.
Symmetric Multithreading
• The basic idea:
1. Create multiple logical processors on the same physical
processor.
2. Present a view of several logical processors to the OS.
• Each logical processor has its own architecture state,
which includes general-purpose and machine-state
registers.
• Each logical processor is responsible for its own interrupt handling.
• SMT is a feature provided in hardware, notsoftware.
THREAD SCHEDULING
• On OSs, it is kernel-level threads but not processes that are being scheduled by
theOS.
• User-level threads are managed by a thread library, and the kernel is unaware
ofthem.
Contention Scope
• Twoapproaches:
1. Process-Contention scope
Page 50 of 60
Operating System 22CSE44
to thesameprocess.
2. System-Contentionscope
▪ The process of deciding which kernel thread to schedule on theCPU.
▪ Competition for the CPU takes place among all threads in thesystem.
▪ Systems using the one-to-one model schedule threads using onlySCS.
Pthread Scheduling
• Pthread API that allows specifying either PCS or SCS during threadcreation.
• Pthreads identifies the following contention scopevalues:
1. PTHREAD_SCOPEJPROCESS schedules threads using PCSscheduling.
2. PTHREAD-SCOPE_SYSTEM schedules threads using SCSscheduling.
• Pthread IPC provides following two functions for getting and setting
the contentionscopepolicy:
1. pthread_attr_setscope(pthread_attr_t *attr, intscope)
2. pthread_attr_getscope(pthread_attr_t *attr, int*scop)
Page 51 of 60
Operating System 22CSE44
Solution-
If the CPU scheduling policy is SJF non-preemptive, calculate the average waiting time and
average turnaround time.
Gantt Chart-
[Link] the set of 5 processes whose arrival time and burst time are given below-
Page 52 of 60
Operating System 22CSE44
If the CPU scheduling policy is SJF pre-emptive, calculate the average waiting time and average
turnaround time.
Solution-
Gantt Chart-
Now,
P1 0 4 2
P2 1 3 3
P3 2 1 4
P4 3 5 5
P5 4 2 5
Page 53 of 60
Operating System 22CSE44
If the CPU scheduling policy is priority non-preemptive, calculate the average waiting time
and average turnaround time. (Higher number represents higher priority)
Solution- Gantt
Chart-
Now, we know-
• Turn Around time = Exit time – Arrival time
• Waiting time = Turn Around time – Burst time
Page 54 of 60
Operating System 22CSE44
[Link] the set of 5 processes whose arrival time and burst time are given below-
Gantt Chart-
Now, we know-
• Turn Around time = Exit time – Arrival time
• Waiting time = Turn Around time – Burst time
Now,
• Average Turn Around time = (15 + 11 + 1 + 5 + 6) / 5 = 38 / 5 = 7.6 unit
• Average waiting time = (11 + 8 + 0 + 0 + 4) / 5 = 23 / 5 = 4.6 unit
Page 55 of 60
Operating System 22CSE44
5. Consider the set of 5 processes whose arrival time and burst time are given below-
If the CPU scheduling policy is Round Robin with time quantum = 2 unit, calculate the average
waiting time and average turnaround time.
Solution:
Gantt Chart-
Now, we know-
• Turn Around time = Exit time – Arrival time
• Waiting time = Turn Around time – Burst time
Page 56 of 60
Operating System 22CSE44
P4 9 9–3=6 6–2=4
P5 14 14 – 4 = 10 10 – 3 = 7
Now,
• Average Turn Around time = (13 + 11 + 3 + 6 + 10) / 5 = 43 / 5 = 8.6 unit
• Average waiting time = (8 + 8 + 2 + 4 + 7) / 5 = 29 / 5 = 5.8 unit
[Link] the set of 6 processes whose arrival time and burst time are given below-
Process Id Arrival time Burst time
P1 0 4
P2 1 5
P3 2 2
P4 3 1
P5 4 6
P6 6 3
If the CPU scheduling policy is Round Robin with time quantum = 2, calculate the average
waiting time and average turnaround time.
Solution-
Ready Queue- P5, P6, P2, P5, P6, P2, P5, P4, P1, P3, P2, P1
Gantt chart-
Now, we know-
• Turn Around time = Exit time – Arrival time
• Waiting time = Turn Around time – Burst time
Page 57 of 60
Operating System 22CSE44
Page 58 of 60
Operating System 22CSE44
MODEL QUESTIONS:
Page 59 of 60
Operating System 22CSE44
21. What are scheduling queues? Explain the job queue, ready queue, and waiting
queue.
22. Define context switch and explain its significance in process management. What
challenges does an OS face during context switching?
23. What are the different operations on processes? Explain the process creation
process in detail. What is process termination, and how does the OS handle it?
24. What is Inter-Process Communication (IPC)? Explain the Shared-Memory system
in IPC. How does Message Passing work in IPC?
25. What is CPU Scheduling, and why is it necessary? Explain the concept of the CPU-I/O
Burst Cycle.
26. How does the OS decide which process to schedule next? Define preemptive and
non-preemptive scheduling. Give examples. How does the Dispatcher minimize CPU
scheduling overhead?
27. List the different CPU Scheduling criteria.
28. Why is CPU utilization an important scheduling criterion?
29. Explain the First-Come, First-Served (FCFS) scheduling algorithm with an example.
30. Describe the Shortest Job First (SJF) scheduling algorithm. Compare preemptive
SJF and non-preemptive SJF scheduling.
31. How does the Round-Robin (RR) scheduling algorithm work?
32. What is Priority Scheduling? How does it affect process execution?
33. What is Starvation in CPU scheduling? How can it be prevented?
34. Explain Aging in the context of Priority Scheduling.
Refer notes for CPU Scheduling Algorithms Problems.
Page 60 of 60