Operating Systems: Process
Operating Systems: Process
Operating Systems
Process
Note:
Some slides and/or pictures are adapted from Lecture slides /
Books of
• Dr Syed Mansoor Sarwar.
• Mr. Arif Butt
• Silberschtaz, Galvin
• William Stalling
1
Introduction to Process
Process – A program in execution.
A Program by itself is not a process.
Program is a passive entity, such as content in a file
stored on disk, whereas Process is an active entity.
Any activity performed by CPU is called Process.
A Process is a unit of work in a system.
System consists of a collection of Processes.
Process execution must progress in sequential fashion.
2
Processes and Resources
3
Components of a Process
A process consists of:
Code (Text) section
Data Section
Stack (Used in function calls to keep parameters,
local variables, return addresses)
Heap (Used to allow a process to request for
allocation/ de-allocation of memory at run time)
Environment (Command line parameters)
CPU State (Program Counter, etc.)
Process Control Block (PCB) (A kernel data structure
allocated to every process) 4
Process Control Box (PCB)
• PCB is the most important and central
data structure in an OS maintained by the
kernel.
• A PCB is a data block or record containing
many pieces of information associated
with a specific process.
• PCB contains sufficient information so
that it is possible to interrupt a running
process and later resume execution as if
the interruption had not occurred.
• The PCB is the key tool that enables the
OS to support multiple processes and to
provide multiprocessing.
5
Process Control Block (PCB)
Process information and attributes
Process ID (PID)
Parent PID
Process state
Program counter
CPU registers
CPU scheduling information
Memory-management information
Accounting information
I/O status information
Per process file table etc.
6
CPU and I/O Bound Processes
I/O-bound process – spends more time doing I/O
than computations, many short CPU bursts.
7
CPU and I/O Bursts of a Process
8
Process States
• Broadly speaking life of a process consists of CPU bursts
and I/O bursts.
• When the OS creates a new process, it creates a
process control block for the process and enters that
process into the system in the Not Running state.
A program that selects which process should be
executed next and allocates it the CPU is called
dispatcher. The process is now in the Running state.
From time to time, the currently running process will be
interrupted and the dispatcher portion of the OS will
select some other process to run.
9
2-State Process Model
• Simplest possible model can be constructed by observing that at
any particular time, a process is either being executed by a
processor or is not running or waiting for an I/O
• There may be a number of processes in the “not running” state
but only one process will be in “running” state
Dispatch
Enter Exit
Not
Running
Running
Pause
Wait for an I/O
10
Queuing Diagram (2-State Process Model)
• Queuing structure for a two state process model is:
Limitations
• If all processes in the queue are always ready to execute only then the above
queuing discipline will work
• But it may also be possible that some processes in the queue are ready to
execute, while some are waiting for an I/O operation to complete
• So the dispatcher has to scan the list of processes looking for the process
that is not blocked and is there in the queue for the longest. This problem is
called Head Of Line (HOL) blocking. 11
5-State Process Model
• Broadly speaking the life of a process consist of CPU burst and I/O
burst but in reality
• A process may be waiting for an event to occur; e.g. a process has created
a child process and is waiting for it to return the result
• A process may be waiting for a resource which is not available at this time
• So generally speaking a Process may be in one of the following
five states:
new: The process is being created (Disk to Memory)
ready: The process is in main memory waiting to be assigned
to a processor
running: Instructions are being executed
waiting: The process is waiting for some event to occur (I/O
completion or reception of a signal)
terminated: The process has finished execution
12
5-State Process Model
14
5-State Process Model
• The New state corresponds to a process that has just been
defined, but has not yet been admitted to the pool of executable
processes by the OS.
• The following steps are performed to bring a process in New
state:
• An identifier is associated with the process.
• Any tables that will be needed to manage the process are allocated and
built.
• At this point, the process is in the New state. This means that the OS has
performed the necessary actions to create the process but has not
committed itself to the execution of the process.
• For example, the OS may limit the number of processes that may be in the
system for reasons of performance or main memory limitation. While a
process is in the new state, information concerning the process that is
needed by the OS is maintained in control tables in main memory.
However, the process itself is not in main memory.
15
Queuing Diagram (5-State Process Model) –
using 2 Queues
16
Queuing Diagram (5-State Process Model) –
using 2 Queues
Limitations:
• When an event occurs, the dispatcher would have to cycle through
the entire Blocked Queue searching for those processes waiting for
that event.
• This can cause huge overhead when there may be 100’s or 1000’s
of processes.
• Therefore, it would be more efficient to have a number of queues,
one for each event.
• Also, If the dispatching of processes is dictated by a priority
scheme, then it would be convenient to have a number of Ready
queues, one for each priority level. The OS could then readily
determine which is the highest-priority ready process that has been
waiting the longest.
17
Queuing Diagram (5-State Process Model) –
using Multiple Queues
18
Process Scheduling Queues
Job queue – set of all processes in the system. When
a process enters the system it is put into a job
Queue.
Ready queue – set of all processes residing in main
memory, ready and waiting to execute. It is generally
stored as a link list
Device queues – set of processes waiting for I/O
devices. Each device has its own device queue
• A process in its life time will be migrating from one Q
to another Q
19
Queues in the OS
20
Queues in a Computer System
21
Schedulers
• A process migrates between various states and scheduling
queues throughout its life cycle.
• OS must select processes from these queues in some
predefined fashion. This selection is done by an appropriate
scheduler.
• “Scheduling is a matter of managing queues to minimize
queuing delay and to optimize performance in a queuing
environment”.
• There are following types of schedulers depending on the
frequency of their use:
Long term scheduler
Short term scheduler
Medium term scheduler
22
Long Term Scheduler
Long-term scheduler (or job scheduler) – selects
processes from the job pool (hard disk) to be brought
into the ready queue (main memory).
Long-term scheduler is invoked very infrequently
(seconds, minutes) (may be slow).
Must select a good mix of I/O bound and CPU bound
processes
The long-term scheduler controls the degree of
multiprogramming. More processes, smaller
percentage of time each process is executed
23
Short Term Scheduler
Short-term scheduler (or CPU scheduler) – selects
which process should be executed next and allocates it
the CPU through the dispatcher.
Short-term scheduler is invoked very frequently
(milliseconds) (must be fast).
Invoked when following events occur
CPU slice of the current process finishes
Current process needs to wait for an event
Clock interrupt
I/O interrupt
System call
Signal 24
Medium Term Scheduler
Also known as swapper
The CPU is so much faster than I/O that it will be common for all
of the processes in memory to be waiting for I/O. Thus even with
multiprogramming the CPU could be idle most of the time.
Solution is “SWAPPING”, which involves moving part or all of the
process from main memory to disk.
When none of the processes in main memory is in the Ready
state, the OS swaps one of the blocked processes out onto disk
Swapping decision is based on several factors
Arrival of a higher priority process but no memory available
Poor mix of jobs
Memory request of a process cannot be met
25
Addition of Medium Term Scheduling
26
6-State Process Model
• With the use of swapping, one other state must be
added: the Suspend state . Blocked state becomes
suspend state when swapped to disk.
When all the processes in main memory are in Block
state (and some other processes wants to come in, but
we don’t have enough memory), the OS can suspend
one process by putting it in the suspended state and
transferring it to disk. This is called a swap-out
operation. Now the main memory has space to bring in a
new process (swap-in).
• The suspended queue consists of the processes that
have been temporarily kicked out of main memory.
27
6-State Process Model
28
6-State Process Model
• Limitation:
• This only allows processes which are blocked to be
swapped out. What if there is no blocked process but we
still need to free up memory?
• Solution:
• Add another state Ready Suspended and swap out a
process from the ready state
29
6-State Process Model
When the OS has performed a swapping-out operation, it has two
choices for selecting a process to bring into main memory:
a) It can admit a newly created process or
b) It can bring in a previously suspended process.
Choice (b) appears to be more appropriate, but it has one
problem associated with it. All of the processes that have been
suspended were in the Blocked state at the time of suspension. It
clearly would not do any good to bring a blocked process back
into main memory, because it is still not ready for execution.
However, it is important to note that each process in the Suspend
state was originally blocked on a particular event. When that
event occurs, the process is not blocked and is potentially
available for execution.
30
7-State Process Model
We need to distinguish between Blocked/Suspended and
Ready/Suspended state of a process.
For this, we need to add another state in the model, resulting in
7-state process model.
31
7-State Process Model
32
Context Switch
When CPU switches to another process, the
system must save the state (context) of the
‘current’ (old) process and load the saved state
for the new process.
Context-switch time is overhead; the system
does no useful work while switching.
The time it takes for a dispatcher to stop one
process and start another is known as dispatch
latency.
Time dependent on hardware support; typically
in microseconds
33
CPU Switch From Process to
Process
34
Process Creation
Parent process create children processes, which, in turn
create other processes, forming a tree of processes.
• Process creation and termination are the only mechanisms
used by the UNIX system to execute external commands
• Once the OS decides to create a process it proceeds as
follows:
• Assigns a unique PID to the new process.
• Allocate space
• Initialize the PCB for that process.
• Set appropriate linkages and data structures
35
Program to print pid and ppid
//prog2.c
#include <stdio.h>
void main main(void){
printf(“Process id = %d”, getpid());
printf(“Parent Process id = %d”,
getppid());
}
36
Process Creation
Resource sharing
Parent and children share all resources
Children share a subset of parent’s resources
Parent and child share no resources
Execution
Parent and children execute concurrently
Parent waits until children terminate
Address space
Child duplicate of parent
Child has a program loaded onto it
UNIX examples
fork() system call creates a new process
exec() system call used after a fork to replace the process
37
memory image with a new executable.
Processes Tree on a UNIX System
38
Process Termination
Process executes the last statement and requests the operating
system to terminate it using the exit() system call.
At this point the process returns data to its parent process.
Process resources are de-allocated by the operating system, to
be recycled later.
Parent may terminate execution of children processes for a
variety of reasons such as:
Child has exceeded allocated resources (main memory,
execution time, etc.)
Parent needs to create another child but has reached its
maximum children limit
Task performed by the child is no longer required
39
Process Termination …
Parent exits.
Operating system does not allow child to continue if its
parent terminates.
Cascaded termination
• A process may terminate due to following reasons:
• Normal completion
• Memory unavailable
• Protection error
• Mathematical error
• I/O failure
• Cascading termination (by OS)
• Operator intervention
40
Process Management in
UNIX/Linux
41
fork()
When the fork system call is executed, a new
process is created which consists of a copy of
the address space of the parent.
This mechanism allows the parent process to
communicate easily with the child process.
SYNOPSIS
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
<sys/types.h>:
/usr/include/sys/types.h 42
fork() ...
On success: (Child process is created)
The return code for fork is zero for the child
process and the process identifier of child is
returned to the parent process.
Both processes continue execution at the
instruction after the fork call.
On failure: (No child process is created)
A -1 is returned to the parent process and errno is
set appropriately to indicate the reason of failure;
no child is created
43
fork()—Sample Code
main()
{
int pid; pid
Parent Process pid==1234
1234
...
pid = fork();
if (pid == 0) {
/* Code for child */ Child Process pid
pid= =
00
...
}
else {
/* Code for parent */
...
}
Kernel Space
...
} 44
Using fork() & exit() system call
PID: 597 Parent PID: 632 Child
1. //fork1.c 1. //fork1.c
2. int main() 2. int main()
3. { 3. {
4. int pid; 4. int pid;
5. pid = fork(); 5. pid = fork();
6. if (pid == -1) 6. if (pid == -1)
7. { 7. {
8. printf (“\nFork failed\n”); 8. printf (“\nFork failed\n”);
9. exit (1); 9. exit (1);
10. } 10. }
11. if (pid == 0) //child code 11. if (pid == 0) //child code
12. printf (“\n Hello I am child \n”); 12. printf (“\n Hello I am child \n”);
13. else //parent code 13. else //parent code
14. printf (“\n Hello I am parent \n”); 14. printf (“\n Hello I am parent \n”);
15. } 15. }
DATA DATA
pid = 632 pid = 0
• After fork parent and child are identical except for the return value of fork (and of course the
PIDs).
• Because data are different therefore program execution differs.
• They are free to execute on their own from now onwards, i.e. after a successful or
unsuccessful fork() system call both will start their execution from line#6.
45
Using fork() & exit() system call
PID: 597 Parent PID: 632 Child
1. //fork1.c 1. //fork1.c
2. int main() 2. int main()
3. { 3. {
4. int pid; 4. int pid;
5. pid = fork(); 5. pid = fork();
6. if (pid == -1) 6. if (pid == -1)
7. { 7. {
8. printf (“\nFork failed\n”); 8. printf (“\nFork failed\n”);
9. exit (1); 9. exit (1);
10. } 10. }
11. if (pid == 0) //child code 11. if (pid == 0) //child code
12. printf (“\n Hello I am child \n”); 12. printf (“\n Hello I am child \n”);
13. else //parent code 13. else //parent code
14. printf (“\n Hello I am parent \n”); 14. printf (“\n Hello I am parent \n”);
15. } 15. }
DATA DATA
pid = 632 pid = 0
• When both will execute line 11, parent will now execute line 14 while
child will execute line 12.
46
fork()—Inherits from the Parent
The child process inherits the following
attributes from the parent:
Environment
Open file descriptor table
Signal handling settings
Nice value
Current working directory
Root directory
File mode creation mask (umask)
47
fork()—Child Differs from the
Parent
48
fork()—Reasons for Failure
Maximum number of processes allowed to
execute under one user has exceeded
Maximum number of processes allowed
on the system has exceeded
Not enough swap space
49
Zombie and Orphan
Zombie process— a process that has terminated but
whose exit status has not yet been received by its parent
process or by init.
Zombie process is half live – half dead, because it is
holding resources such as PCB, memory but it is never
scheduled by OS.
Orphan process – a process that is still executing but
whose parent has died. They do not become zombie
rather are adopted by init process
50
wait()
The wait system call suspends the calling process until
one of its immediate children terminates, or until a child
that is being traced stops because it has hit an event of
interest.
wait returns prematurely if a signal is received. If all
children processes stopped or terminated prior to the call
on wait, return is immediate.
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *stat_loc);
<sys/wait.h>:
/usr/include/sys/wait.h 51
wait() ...
If the call is successful, the process ID of the terminating
child is returned.
If parent terminates all its children have assigned as their
new parent, the init process. Thus the children still have a
parent to collect their status and execution statistics.
52
Sample Code—fork(), wait() and exit()
#include <stdio.h>
void main()
{
int pid, status;
pid = fork();
if(pid == -1) {
printf(“fork failed\n”);
exit(1); }
if(pid == 0) { /* Child */
printf(“Child here!\n”);
exit(0); }
else { /* Parent */
wait(&status);
printf(“Well done kid!\n”);
exit(0); }
53
}
exec()
54
Synopsis of exec()
#include <unistd.h>
int execlp (const char *file, const
char *arg0, ..., const char *argn,
(char *)0);
55
Sample Code—fork and exec
#include <stdio.h>
void main()
{
int pid, status;
pid = fork();
if(pid == -1) {
printf(“fork failed\n”);
exit(1);
}
if(pid == 0) { /* Child */
if (execlp(“/bin/ls”, “ls”, NULL)< 0) {
printf(“exec failed\n”);
exit(1); }
}
else { /* Parent */
wait(&status);
printf(“Well done kid!\n”);
exit(0);
}
} 56
Semantics of fork
P P P
fork
P P ls
exec ls
child child child
57
1 2 3
Process Management Commands in
UNIX/Linux
58
Process Management Commands in
UNIX/Linux
59
Process Creation in Windows
• CreateProcess() function similar to fork() is used.
• However, whereas fork() has a child process
inheriting the address space of its parent,
CreateProcess() requires loading a specified program
into the address space of the child process at the
process creation.
• Furthermore, fork() is parameter less,
CreateProcess() accepts no fewer than 10
parameters.
60