You are on page 1of 18

MODULE II

2.1 PROCESS CONCEPT


➢ Process is a program in execution. A process is the unit of work in a modern
time-sharing system.
➢ An operating system executes a variety of programs:
- Batch system – jobs
- Time-shared systems – user programs or tasks
The Process
➢ A process is more than the program code, it includes
- The program code, also called text section
- Current activity including program counter, processor registers
- Stack containing temporary data
 Function parameters, return addresses, local variables
- Data section containing global variables
-Heap containing memory dynamically allocated during run time
➢ program is a passive entity(executable files), whereas a process is an active
entity
➢ A program becomes a process when an executable file is loaded into memory.

Process in memory
Process State

➢ As a process executes, it changes state.


➢ The state of a process is defined in part by the current activity of that process.

➢ Each process may be in one of the following states:


➢ new: The process is being created
➢ running: Instructions are being executed
➢ waiting: The process is waiting for some event to occur
➢ ready: The process is waiting to be assigned to a processor
➢ terminated: The process has finished execution
➢ Only one process can be running on any processor at any instant. Many
processes may be ready and waiting.

Module 2 1
Diagram of process state

Process Control Block


➢ Each process is represented on the OS by a Process Control Block(PCB) also
called a task control block..
➢ It includes
o Process state – The state may be new, ready running, waiting, halted
etc
o Program counter – The counter indicates the address of the next
instruction to be executed for this process.
o 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, plus any condition-code
information. Along with the program counter, this state information
must be saved when an interrupt occurs, to allow the process to be
continued correctly afterward

o CPU scheduling information- includes a process priority, pointers to


scheduling queues, and any other scheduling parameters.

Module 2 2
o Memory-management information -include such information as the
value of the base and limit registers, the page tables, or the segment
tables, depending on the memory system used by the operating
system.
o Accounting information –includes the amount of CPU and real time
used, time limits, account numbers, job or process numbers, and so on.
o I/O status information – I/O devices allocated to process, list of open
files

Process Control Block


Threads
➢ Process is a program that performs single thread of execution.
➢ Single thread of control allows the process to perform only one task at one
time.
➢ Modern Operating Systems have extended the process concept to allow a
process to have multiple threads of execution and thus to perform more than
one task at a time.

2.2 PROCESS SCHEDULING


➢ The objective of time sharing is to switch the CPU among processes so frequently
that users can interact with each program while it is running.
➢ The process scheduler selects an available process for program execution on the
CPU.
➢ Maintains scheduling queues of processes
o Job queue – set of all processes in the system
o Ready queue – set of all processes residing in main memory, ready
and waiting to execute
o Device queues – set of processes waiting for an I/O device
o Processes migrate among the various queues

Module 2 3
Queuing diagram representation of process scheduling
➢ A new process is initially put in the ready queue. It waits there until it is
selected for execution, or is dispatched. Once the process is allocated the
CPU and is executing, one of several events could occur:
➢ The process could issue an I/0 request and then be placed in an I/0 queue.
➢ The process could create a new subprocess and wait for the subprocess's
termination.
➢ The process could be removed forcibly from the CPU, as a result of an
interrupt, and be put back in the ready queue

Schedulers

➢ A process migrates among the various scheduling queues throughout its


lifetime.
➢ The operating system must select, for scheduling purposes, processes from
these queues in some fashion.
➢ The selection process is carried out by the appropriate scheduler
➢ The long-term scheduler, or job scheduler, selects processes from pool and
loads them into memory for execution. Long-term scheduler is invoked
infrequently (seconds, minutes).
➢ The short-term scheduler, or CPU scheduler, selects from among the processes
that are ready to execute and allocates the CPU to one of them. Short-term
scheduler is invoked frequently (milliseconds)  (must be fast)
➢ Processes can be described as either:
➢ I/O-bound process – spends more time doing I/O than computations, many
short CPU bursts
➢ CPU-bound process – spends more time doing computations; few very long
CPU bursts
➢ Long-term scheduler strives for good process mix of I/O-bound and CPU-bound
processes.
➢ Medium-term scheduler can be added if degree of multiple programming
needs to decrease
➢ Swapping -Remove process from memory, store on disk, bring back in from
disk to continue execution

Module 2 4
Addition of medium-term scheduling to the queuing diagram

Context Switch

➢ When CPU switches to another process, the system must save the state of
the old process and load the saved state for the new process via a context
switch
➢ Context of a process represented in the PCB
➢ Context-switch time is overhead; the system does no useful work while
switching
➢ The more complex the OS and the PCB ➔ the longer the context switch
➢ Time dependent on hardware support
➢ Some hardware provides multiple sets of registers per CPU ➔ multiple
contexts loaded at once.

2.3 OPERATIONS ON PROCESSES


➢ System must provide mechanisms for:
➢ process creation,
➢ process termination,

Process Creation
➢ A process may create several new processes, via a create-process system
call,during the course of execution.
➢ The creating process is called a parent process, and the new processes are
called the children of that process. Each of these new processes may in turn
create other processes, forming a tree of processes.
➢ Generally, process identified and managed via a process identifier (pid)
➢ Resource sharing options
➢ Parent and children share all resources
➢ Children share subset of parent’s resources
➢ Parent and child share no resources

Execution options

➢ Parent and children execute concurrently


➢ Parent waits until children terminate

Possibilities in terms of the address space of the new process

Module 2 5
➢ The child process is a duplicate of the parent process
➢ The child process has a new program loaded into it.

UNIX examples

➢ fork() system call creates new process


➢ exec() system call used after a fork() to replace the process’
memory space with a new program

C program forking a separate process

Process Termination
➢ Process executes last statement and then asks the operating system to delete it
using the exit() system call
➢ Returns status data from child to parent (via wait())
➢ Process’ resources are deal located by operating system
➢ A process can cause the termination of another process via an appropriate
system call. Such a system call can be invoked only by the parent of the
process that is to be terminated
➢ A parent needs to know the identities of its children. Thus, when one process
creates a new process, the identity of the newly created process is passed to
the parent.

Module 2 6
pid t pid;
int status;

pid = wait(&status);
➢ A parent may terminate the execution of one of its children for a variety of
reasons, such as these:
o Child has exceeded allocated resources
o Task assigned to child is no longer required
o The parent is exiting and the operating systems does not allow a child
to continue if its parent terminates
➢ Some operating systems do not allow child to exist if its parent has
terminated. If a process terminates, then all its children must also be
terminated. This phenomenon, referred to as cascading termination. The
termination is initiated by the operating system
➢ The parent process may wait for termination of a child process by using the
wait()system call. The call returns status information and the pid of the
terminated process

2.4 INTERPROCESS COMMUNICATION

➢ Inter process communication (IPC) refers to the coordination of activities among


cooperating processes.
➢ Reasons for cooperating processes:
o Information sharing
o Computation speedup
o Modularity
o Convenience
➢ Two models of IPC
o Shared memory-
o Message passing

Module 2 7
Shared-Memory Systems
➢ Interprocess communication using shared memory requires communicating
processes to establish a region of shared memory.
➢ A shared-memory region resides in the address space of the process creating
the shared memory segment. Other processes that wish to communicate using
this shared memory segment must attach it to their address space.
➢ They can then exchange information by reading and writing data in the
shared areas.
➢ The communication is under the control of the users processes not the
operating system.
➢ Example for cooperating processes.:-Producer-consumer problem.
o A producer process produces information that is consumed by a
consumer process.
o One solution to the producer-consumer problem uses shared memory.
o A buffer which reside in a region of memory that is shared by the
producer and consumer processes is used
o The producer and consumer must be synchronized, so that the
consumer does not try to consume an item that has not yet been
produced
o Two types of buffers can be used.
▪ unbounded-buffer places no practical limit on the size of the
buffer
▪ bounded-buffer assumes that there is a fixed buffer size

➢ Bounded-Buffer – Shared-Memory Solution


Shared data
#define BUFFER_SIZE 10
typedef struct {
...
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
➢ The shared buffer is implemented as a circular array with two logical
pointers: in and out.
➢ The variable in points to the next free position in the buffer; out points to the
first full position in the buffer.
➢ The buffer is empty when in== out; the buffer is full when ((in+ 1)%
BUFFER_SIZE) == out.
➢ Producer
item next_produced;
while (true) {

Module 2 8
/* produce an item in next produced */
while (((in + 1) % BUFFER_SIZE) == out)
; /* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
}

➢ Consumer
item next_consumed;
while(true){
while (in == out)
;/*donothing*/
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
/* consume the item in next consumed */
}

Message-Passing Systems
➢ Message passing provides a mechanism to allow processes to communicate
and to synchronize their actions without sharing the same address space.
➢ A message-passing facility provides at least two operations: send (message)
and receive (message).
➢ If processes P and Q want to communicate, they must send messages to and
receive messages from each other; a communication link must exist between
them.
➢ methods for logically implementing a link and the send() /receive()
operations:
o Direct or indirect communication.
o Synchronous or asynchronous communication.
o Automatic or explicit buffering

Naming
➢ Processes that want to communicate must have a way to refer to each other.
They can use either direct or indirect communication. Under direct
communication, each process that wants to communicate must explicitly
name the recipient or sender of the communication. In this scheme, the send()
and receive() primitives are defined as:
o send(P, message) -Send a message to process P.
o receive (Q, message)-Receive a message from process Q.

Module 2 9
➢ Symmetry in addressing- both the sender process and the receiver process
must name the other to communicate.
➢ Asymmetry in addressing- Here, only the sender names the recipient; the
recipient is not required to name the sender.
o send (P, message) -Send a message to process P.
o receive (id, message) -Receive a message from any process
➢ With indirect communication, the messages are sent to and received from
mailboxes, or ports.
➢ Two processes can communicate only if the processes have a shared mailbox.
o send (A, message) -Send a message to mailbox A.
o receive (A, message)-Receive a message from mailbox A.
➢ The operating system must provide a mechanism that allows a process to do
the following:
o Create a new mailbox.
o Send and receive messages through the mailbox.
o Delete a mailbox.

Synchronization
➢ Message passing may be either blocking or nonblockingalso known as
synchronous and asynchronous.
o Blocking send. The sending process is blocked until the message is
received by the receiving process or by the mailbox.
o Nonblocking send. The sending process sends the message and
resumes operation.
o Blocking receive. The receiver blocks until a message is available.
o Nonblocking receive. The receiver retrieves either a valid message or a
null.

Buffering
➢ Whether communication is direct or indirect, messages exchanged by
communicating processes reside in a temporary queue. Basically, such queues
can be implemented in three ways:
o Zero capacity -The queue has a maximum length of zero; thus, the link
cannot have any messages waiting in it. In this case, the sender must
block until the recipient receives the message.
o Bounded capacity. The queue has finite length n; thus, at most n
messages can reside in it. If the queue is not full when a new message
is sent, the message is placed in the queue, and the sender can continue
execution without waiting. The link's capacity is finite. If the link is
full, the sender must block until space is available in the queue.
o Unbounded capacity. The queue's length is potentially infinite; thus,
any number of messages can wait in it. The sender never blocks.

Module 2 10
PIPES
A pipe acts as a conduit allowing two processes to communicate. Pipes were one
of the first IPC mechanisms in early UNIX systems and typically provide one of the
simpler ways for processes to communicate with one another.

Ordinary Pipes

Ordinary pipes allow two processes to communicate in standard producer consumer


fashion; the producer writes to one end of the pipe(write end) and the consumer
reads from the other end(read end). As a result, ordinary pipes are unidirectional,
allowing only one-way communication. If two-way communication is required, two
pipes must be used, with each pipe sending data in a different direction. One process
writes the message to the pipe, while the other process reads this message from the
pipe.
On UNIX systems, ordinary pipes are constructed using the function pipe (int fd
[]) This function creates a pipe that is accessed through the int fd [] file descriptors:
fd [0] is the read-end of the pipe, and fd [1] is the write end.

File descriptors for an ordinary pipe.

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
main()
{
int fd[2];
char str[100];
pid_t pid;
pid=fork();
if(pid==0)
{
read(fd[0],str,sizeof(str));
printf(“inside the child process\n”);
printf(“\n message from parent is %s”,str);
printf(“\nenter the message to parent\n”);
gets(str);
write(fd[1],str,sizeof(str));
}
Module 2 11
else
{
printf(“insert the parent process\n”);
printf(“message from parent\n);
gets(str);
write(fd[1],str,sizeof(str));
sleep(2);
read(fd[0],str,sizeof(str));
printf(“message from child is %s”,str);
}
}

Named Pipes

Ordinary pipes provide a simple communication mechanism between a


pair of processes. However, ordinary pipes exist only while the processes are
communicating with one another. On both UNIX and Windows systems, once
the processes have finished communicating and terminated, the ordinary pipe
ceases to exist.
Named pipes provide a much more powerful communication tool;
communication can be bidirectional, and no parent-child relationship is required.
Once a named pipe is established, several processes can use it for
communication. In fact, in a typical scenario, a named pipe has several writers.
Additionally, named pipes continue to exist after communicating processes have
finished.
Both UNIX and Windows systems support named pipes. Named pipes are
referred to as FIFOs in UNIX systems. Once created, they appear as typical files
in the file system. A FIFO is created with the mkfifo() system call and
manipulated with the ordinary open(), read(), write(), and close () system calls. It
will continue to exist until it is explicitly deleted from the file system. Although
FIFOs allow bidirectional communication, only half-duplex transmission is
permitted. If data must travel in both directions, two FIFOs are typically used.

CPU SCHEDULING
Basic concepts
➢ Maximum CPU utilization obtained with multiprogramming

CPU-I/O Burst Cycle


➢ Process execution consists of a cycle of CPU execution and I/0 wait. Processes
alternate between these two states.

Module 2 12
➢ Process execution begins with a CPU burst.
➢ Final CPU burst ends with a system request to terminate execution.

Alternating sequence of CPU and 1/0 bursts.


➢ An I/O-bound program typically has many short CPU bursts. A CPU-bound
program might have a few long CPU bursts.
➢ This distribution can be important in the selection of an appropriate CPU-
scheduling algorithm
CPU Scheduler
➢ Whenever the CPU becomes idle, the operating system must select one of the
processes in the ready queue to be executed. The selection process is carried
out by the short-term scheduler (or CPU scheduler).
➢ The scheduler selects a process from the processes in memory that are ready
to execute and allocates the CPU to that process.
➢ A ready queue can be implemented as a FIFO queue, a priority queue, a tree,
or sirnply an unordered linked list.
➢ The records in the queues are generally process control blocks (PCBs) of the
processes.

Preemptive Scheduling

➢ CPU-scheduling decisions may take place under the following four


circumstances:
1. When a process switches from the running state to the waiting state
2. When a process switches from the running state to the ready state.
3. When a process switches from the waiting state to the ready state
4. When a process terminates
➢ Scheduling under 1 and 4 is nonpreemptive.
➢ All other scheduling is preemptive
➢ Consider access to shared data
➢ Consider preemption while in kernel mode
Module 2 13
➢ Consider interrupts occurring during crucial OS activities
Dispatcher
➢ Dispatcher module gives control of the CPU to the process selected by the
short-term scheduler; this involves:
1. Switching context
2. Switching to user mode
3. Jumping to the proper location in the user program to restart that
program
➢ The time it takes for the dispatcher to stop one process and start another
running is known as the dispatch latency.

Scheduling Criteria
➢ Many criteria have been suggested for comparing CPU-scheduling
algorithms.
➢ The criteria include the following:
1. CPU utilization- Keep the CPU as busy as possible.
2. Throughput – Number of processes that complete their execution per
time unit
3. Turnaround Time-The interval from the time of submission of a
process to the time of completion. Turnaround Time is the sum of the
periods spent waiting to get into memory, waiting in the ready queue,
executing on the CPU, and doing I/0 waiting time.
4. Waiting Time-sum of the periods spent waiting in the ready queue.
5. Response Time- – amount of time it takes from when a request was
submitted until the first response is produced, not output (for time-
sharing environment)

SCHEDULING ALGORITHMS

First- Come, First-Served (FCFS) Scheduling


➢ The process that requests the CPU first is allocated the CPU first.
➢ The implementation of the FCFS policy is easily managed with a FIFO queue.
➢ When a process enters the ready queue, its PCB is linked onto the tail of the
queue.
➢ When the CPU is free, it is allocated to the process at the head of the queue.
➢ The running process is then removed from the queue.

Process Burst Time


P1 24
P2 3
P3 3
➢ Suppose that the processes arrive in the order: P1 , P2 , P3

Module 2 14
➢ The Gantt Chart for the schedule is:
P1 P2 P3
0 24 27 30

➢ Waiting time for P1 = 0; P2 = 24; P3 = 27


➢ Average waiting time: (0 + 24 + 27)/3 = 17
➢ Suppose that the processes arrive in the order: P2 , P3 , P1
➢ The Gantt chart for the schedule is:
P2 P3 P1
0 3 6 30

➢ Waiting time for P1 = 6; P2 = 0; P3 = 3


➢ Average waiting time: (6 + 0 + 3)/3 = 3
➢ Convoy effect -All the processes wait for the one big process to get off the CPU.
➢ FCFS scheduling algorithm is Non-preemptive.

Shortest-Job-First Scheduling

➢ This algorithm associates with each process the length of the process's next
CPU burst. When the CPU is available, it is assigned to the process that has
the smallest next CPU burst.
➢ More appropriate term for this scheduling method would be the shortest-
next-CPU-burst algorithm.

Process Burst Time


P1 6
P2 8
P3 7
P4 3
➢ SJF scheduling chart:

P4 P1 P3 P2
0 3 9 16 24
➢ Average waiting time = (3 + 16 + 9 + 0) / 4 = 7
➢ SJF is optimal – Gives minimum average waiting time for a given set of
processes.
➢ The difficulty is knowing the length of the next CPU request.
➢ Can only estimate the length – should be similar to the previous one
• Then pick process with shortest predicted next CPU burst
➢ Can be done by using the length of previous CPU bursts, using exponential
averaging

1. t n = actual length of n th CPU burst


2.  n +1 = predicted value for the next CPU burst
Module 2 3.  , 0    1 15
4. Define :
➢ Commonly, α set to ½
➢ Preemptive version called shortest-remaining-time-first
➢  =0
➢ n+1 = n
➢ Recent history does not count

➢  =1
➢ n+1 =  tn
➢ Only the actual last CPU burst counts
➢ If we expand the formula, we get:
➢ n+1 =  tn+(1 - ) tn -1 + … +(1 -  )j  tn -j + … +(1 -  )n +1 0
➢ Since both  and (1 - ) are less than or equal to 1, each successive term has
less weight than its predecessor
➢ A preemptive SJF algorithm will preempt the currently executing process,
whereas a nonpreemptive SJF algorithm will allow the currently running
process to finish its CPU burst.
➢ Preemptive SJF scheduling is sometimes called shortest-remaining-time-first
scheduling.
➢ Now we add the concepts of varying arrival times and preemption to the
analysis
Process Arrival Time Burst Time

P1 0 8
P2 1 4
P3 2 9
P4 3 5

➢ Preemptive SJF Gantt Chart

P1 P2 P4 P1 P3
0 1 5 10 17 26

➢ Average waiting time = [(10-1)+(1-1)+(17-2)+5-3)]/4 = 26/4 = 6.5 msec

Priority Scheduling

➢ A priority number (integer) is associated with each process


➢ The CPU is allocated to the process with the highest priority (smallest integer
 highest priority)
➢ Preemptive

Module 2 16
➢ Nonpreemptive

ProcessA Burst Time Priority

P1 10 3
P2 1 1
P3 2 4
P4 1 5
P5 5 2

➢ Priority scheduling Gantt Chart


P1 P2 P1 P3 P4
0 1 6 16 18 19

➢ Average waiting time = 8.2 msec


➢ Priorities can be defined either internally or externally.
➢ A rnajor problem with priority scheduling algorithms is indefinite blocking,
or starvation, leaving low priority processes waiting indefinitely.
➢ Solution for starvation is Aging, a technique of gradually increasing the
priority of processes that wait in the system for a long time.

Round-Robin Scheduling
➢ The round-robin (RR) scheduling algorithm is designed especially for
timesharing systems.
➢ Each process gets a small unit of CPU time (time quantum q), usually 10-100
milliseconds. After this time has elapsed, the process is preempted and
added to the end of the ready queue.
➢ If there are n processes in the ready queue and the time quantum is q, then
each process gets 1/n of the CPU time in chunks of at most q time units at
once. No process waits more than (n-1)q time units.
➢ Timer interrupts every quantum to schedule next process
➢ Performance
➢ q large  FIFO
➢ q small  q must be large with respect to context switch,
otherwise overhead is too high
➢ Example of RR with Time Quantum = 4
Process Burst Time
P1 24
P2 3
P3 3

Module 2 17
➢ The Gantt chart is:

P1 P2 P3 P1 P1 P1 P1 P1
0 4 7 10 14 18 22 26 30
➢ Typically, higher average turnaround than SJF, but better response
➢ q should be large compared to context switch time
➢ q usually 10ms to 100ms, context switch < 10 microsecond

➢ Turnaround time also depends on the size of the time quantum.


➢ In general, the average turnaround time can be improved if most processes
finish their next CPU burst in a single time quantum.

Module 2 18

You might also like