You are on page 1of 90

Lecture 2

Process Management
Course out line
❑ Processes and Threads
➢ Process concept
➢ Inter-process Communication
✓ Classical IPC problems
➢ Process scheduling
➢ Deadlock
➢ Thread concept
➢ Single thread and multithread programming
❑ Basic process and thread management in Linux-creating,
monitoring, and killing processes and threads in Linux
Common OS System Components
▪ Process Management and CPU scheduling
▪ MM management
▪ File management
▪ I/O system management
▪ Secondary storage management
▪ Networking
▪ Protection system
▪ Command-Interpreter system
Process
✓ An instance of a program running on a computer.
✓ A process has its own address space, file handles,
security attributes, threads, etc.
✓ A process needs certain resources, including CPU
time, memory, file, and I/O devices, to accomplish its
task.
Process vs program
Process Program
Process is a dynamic object Program is a static object
It is sequence of It is a sequence of instructions
instruction execution
Process loaded in to main Program loaded into secondary
memory storage devices
Time span of process is Time span of program is unlimited
limited
Process is a active entity Program is a passive entity
Process Management
❑The OS is responsible for the following activities in
connection with process management.

▪ Process creation and deletion

▪ Process suspension and resumption

▪ Provision of mechanisms for:


✓Process synchronization

✓Process communication
Creation of a process
▪ When a new process is added, OS builds various data
structures to manage the newly added process.

▪ It also allocates space to the process in memory.

▪ Reason to create a new process :


✓ New batch job

✓ A new user logs on

✓ Created by OS to provide a service


Creation of a process
▪ Spawned by exiting process: the act of creating a new process
(child process) at the explicit request of another process (Parent
process) is called process spawning.

e.g. A printer server or file server may generate a new process for
each request that it handles.
Process Termination
✓Normal completion
✓Time limit exceeded: iteration process
✓Memory unavailable: the limit on max. no. of process
✓Bound violation: access to memory location
✓Protection error: writing to a read-only file
✓Arithmetic error: divide by zero
✓Time overrun: waiting for i/o for infinite time
✓i/o failure, invalid instruction, privileged instruction
✓OS intervention: deadlock occurs, parent termination, parent request
• A small dispatcher program is used to switch the processor from one
process to another.

Two State Process Model 11


Process States …

Five state process model diagram 12


Process state
The process can be any of the following states:

Now – the process is being created.

Ready – the process is waiting to be assigned to a processor.

Running – instructions are being executed.

Waiting – the process is waiting for some event to occur.

Termination – the process has finished execution.


Possible Transition
Null – New: new process is created to execute a problem
New – Ready
Ready -- Running
Running – Exit
Running – Ready
Running – Blocked/waiting
Blocked – Read
Ready – Exit (not shown in the diagram)
Blocked -- exit
Reason for Process suspension
Swapping: OS needs to release sufficient main memory to bring in a
process that is ready to execute.

Other OS reasons: OS may suspend a backend process.

Timing: The process needs periodic execution

Parent Process request: to co-ordinate

Interactive user input: user wants to suspend the process for debugging
purposes.
Process state transition with suspended states
New Termination
Blocked → Blocked/Suspend
Blocked/Suspend → Ready/Suspend
Ready/Suspend → Ready
Ready → Ready/Suspend
New → Ready/Suspend and New – Ready
Blocked/Suspend → Blocked
Running → Ready/Suspend
Any state → exit
Characteristics of Suspended process
✓The process is not immediately available for execution.

✓The process may or may not wait for the event.

✓If waiting and if the event takes place, the process cannot be
executed immediately.

✓Either the process itself or OS makes the state process suspended.


Process image consists of
✓User data
✓User program
✓Stack
✓Process control block
Process control block: stores information of 3 categories

A) Process identification C) Process control information


✓Id of the process
✓ Scheduling and Stating
✓Id of the Parent process
✓User Id information
✓ Data structuring
B) Process state information
✓ Process privileges
✓User-visible registers
✓Control and status ✓ Memory management
registers
✓Stack pointer
✓ Resource ownership and
utilization
PCB
(process control block)
Process…
• Accounting information: This information includes the amount of CPU
and real-time used, time limits, account numbers, job or process
numbers, and so on.

• status information: The information includes the list of I/O devices


allocated to this process, a list of open files(Active files), and so on.

• The process control block is the key tool that enables the OS to support
multiple processes and to provide for multiprocessing.
22
Process List structure
Process States …
• Any computer system must provide a means
for a process to indicate its completion.

• A batch job should include a Halt instruction


or an explicit OS service call for termination.

• In the former case, the Halt instruction will


generate an interrupt to alert the OS that a
process has been completed.
24
Process States…
• Process can be executed in one of the following modes:
➢User mode
➢Kernel mode
• Considerations of memory protection and privileged
instructions lead to the concept of modes of operation.
• A user program executes in a user mode
• The monitor executes in a system mode, or called kernel
mode, in which privileged instructions may be executed and
in which protected areas of memory may be accessed.
25
Context Switching
✓ 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

✓ Time dependent on hardware support


Cooperating Process
▪ Independent process cannot affect or be affected by the
execution of another process.

▪ The cooperating process can affect or be affected by the


execution of another process

▪ Advantages of process cooperation


✓ Information sharing

✓ Computation speed-up

✓ Modularity – fundamental principle of programming

✓ Convenience
Inter-process Communication (IPC)
Why IPC
✓Each process has its own address space.

✓Provides data isolation.

✓Prevents harmful direct interaction between two

different process.
IPC mechanisms
In GRU/Linux
✓Signal
✓Pipe
✓Socket
✓Semaphore
✓Message queue
✓Shared memory
In android
✓Binder: lightweight RPC (Remote procedure
communication) mechanism.
Binder: Android’s solution
✓Driver to facilitate inter-process communication

✓High performance through shared memory

✓Per process thread pool for processing requests

✓Reference counting, and mapping of object references


across processes

✓Synchronous calls between processes


Reading Assignment

Classical IPC problems


Thread
✓ A thread is a flow of execution through the process code, with its own

the program counter, system registers, and stack.

✓ A thread is called the lightweight process.

✓Process is the program under action whereas a thread is the smallest


segment of instructions that can be handled independently by a scheduler.

✓Can re-read the shared data.


Comparison Process Threads
Definition Execution of any program is a Segment or subset of a process is a
process thread
Communication It talks more time to It talks less time for the
communicate between the communications
different processes
Resources It consumes more resource It consumes less resource
Memory The process does not share the Thread are used to share their
memory and is carried out alone memory
Data sharing Process does not share their data Threads share their data
Size The process consumes more size Threads are lightweight
Execution error One process will not affect any Threads will not run if one thread
other process due to an error has an error
Termination Process usually takes more time Threads take less time to terminate
time to terminate
Thread Library
▪ Thread library provides the programmer with API
for creating and managing threads.

▪ Two primary ways of implementing are


✓ Library entirely in user space

✓ Kernel-level library supported by the OS


Thread Synchronization
▪ All of the threads of a process share the same address space and
other resources, such as open files.
▪ Any alteration of a resource by one thread affects the
environment of the other threads in the same process.
▪ It is necessary to synchronize the activities of the various threads
so that they do not interfere with each other or corrupt data
structures.
▪ For example, if two threads each try to add an element to a
doubly linked list at the same time, one element may be lost or the
list may end up malformed.
36
Threads…
▪ There are two broad categories of thread implementation:
user-level threads (ULTs) and kernel-level threads (KLTs).

37
• User Threads Kernel Thread
❑ Thread management done by ❑ Supported by the Kernel

user-level threads library Examples

➢ Three primary thread libraries: ✓ Windows XP/2000

✓ POSIX P threads ✓ Solaris or Linux

✓ Win32 threads ✓ Tru64 UNIX


✓ Java threads ✓ Mac OS X
Difference between user level and kernel level thread
S.N User level threads Kernel level Threads
1 faster to create and manage Slower to create and manage
2 Implementation is by a thread OS supports creation of
libraries at the user level kernel threads
3 It is generic and can run on It is specific to the OS
any OS
4 Multi-threaded application can Kernel routines themselves
not take advantage of can be multithreaded
multiprocessing
Java Threads
▪ Java threads are managed by the JVM

▪ Typically implemented using the threads model


provided by the underlying OS

▪ Java threads may be created by:


✓ Extending Thread class

✓ Implementing the Runnable interface


Threads…
The key benefits of threads derive from the performance
implications:

1. It takes far less time to create a new thread in an


existing process than to create a brand-new process.

2. It takes less time to terminate a thread than a process.

41
Thread …

−Responsiveness
Benefits −Resource Sharing
− Economy
− Scalability
Types of Multiprocessor Systems:

The multiprocessor systems are further divided


into two types;

(I). Asymmetric multiprocessing system (AMP)

(II). Symmetric multiprocessing system (SMP)


Asymmetric Multiprocessing System(AMS)
▪ The multiprocessing system, in which each processor is assigned a
specific task, is known as ASM.
▪ For example, one processor is dedicated for handling user's requests,
one processor is dedicated for running application program, and one
processor is dedicated for running image processing and so on.
▪ In this system, one processor works as master processor, while other
processors work as slave processors.
▪ The master processor controls the operations of system.
▪ It also schedules and distributes tasks among the slave processors.
▪ The slave processors perform the predefined tasks.
Symmetric Multiprocessing System(SMP)
✓The multiprocessing system, in which multiple processors work
together on the same task, is known as Symmetric Multiprocessing
System.
✓In this system, each processor can perform all types of tasks. All
processors are treated equally and no master-slave relationship
exists between the processors.
✓For example, different processors in the system can communicate
with each other. Similarly, an I/O can be processed on any
processor.
Symmetric Multiprocessing System(SMP)
✓However, I/O must be controlled to ensure that the data reaches the
appropriate processor. Because all the processors share the same memory,
so the input data given to the processors and their results must be
separately controlled.
✓ Today all modern operating systems including Windows and Linux
provide support for SMP.
✓In the same computer system, the asymmetric multiprocessing and
symmetric multiprocessing technique can be used through different
operating systems.
Clustered Systems
▪ It is another form of multiprocessor system.

▪ This system also contains multiple processors but it differs from


multiprocessor system.

▪ The clustered system consists of two or more individual systems


that are coupled together.

▪ In clustered system, individual systems (or clustered computers)


share the same storage and are linked together ,via Local Area
Network (LAN).

▪ (i). Asymmetric Clustered System (ii). Symmetric Clustered System


SMP Architecture …
▪ Single instruction single data (SISD) stream

▪ Single instruction multiple data (SIMD)

▪ Multiple instruction single data (MISD)

▪ Multiple instruction multiple data (MIMD)

48
SMP Architecture …

49
MICROKERNELS
• A microkernel is a small OS core that provides the foundation for
modular extensions.
• A microkernel is one of the classifications of the kernel. Being a
kernel it manages all system resources.
• But in a microkernel, the user services and kernel services are
implemented in different address spaces.
• The user services are kept in user address space, and kernel
services are kept under kernel address space, thus also reduces the
size of kernel and size of an operating system as well. 50
MICROKERNELS…

51
The microkernel is solely responsible for the most
important services of the operating system, these are:
• Inter process-Communication

• Memory Management

• CPU-Scheduling
The five main types of kernels are:
✓ Monolithic Kernel.
✓ Microkernel.
✓ Hybrid Kernel.
✓ Nano Kernel.
✓ Exo Kernel.
▪A Kernel in an operating system
performs the following functions:
✓ Device Management
✓ Resource Management
✓ Memory Management
✓ Access Computer Resource
Kernel vs Microkernel
• Kernel is a core feature of any operating system, the kernel manages
communication between hardware and software.
• The kernel is responsible for managing memory, and I/O to memory,
cache, the hard drive, and other devices.
• It also handles device signals, task scheduling, and other essential duties.
• The kernel is one of the first components loaded into memory during the
boot process, and remains active as long as the computer is operational.
• Kernels vary widely in function and scope, but always greatly affect their
operating system's capabilities.
• For this reason, particularly in Unix, administrators tweak the kernels to
best suit their requirements.
Kernel vs Microkernel
✓microkernel is compact, performing only the basic functions universal to
all computers.
✓Designed to be integrated into different operating systems, a microkernel
works with OS-specific servers that provide higher level functions.
✓This component-based structure improves a system's portability, but
potentially at the expense of performance.
✓ Mach and its derivatives, the most prominent examples of the
microkernel architecture, are the foundations of systems such as Tru64
Unix, the GNU Hurd, and Mac OS X.
Benefits of a Microkernel Organization
• Uniform interfaces
• Message Passing Facilities
• Extensibility
• Flexibility
• Portability
• Reliability
• Distributed system support
• Support for object-oriented operating systems (OOOSS)
58
Single thread and multithread programming
✓Single threaded processes contain the execution of instructions in a
single sequence, (one command is processes at a time).

✓Multithreaded processes allow the execution of multiple parts of a


program at the same time.

✓These are lightweight processes available within the process.

✓Multithreaded processes can be implemented as user-level threads


or kernel-level threads.
▪ CODE - Contains instruction

▪ DATA - holds global variable

▪ FILES - opening and closing files

▪ REGISTER - contain information about CPU state

▪ STACK - parameters, local variables, functions


Multithreading Models

✓ Many to many relationship.

✓ Many to one relationship.

✓ One to one relationship.


One-to-One
✓ Each user-level thread
maps to the kernel thread
✓ Examples o Windows
NT/XP/2000
✓ Linux
✓ Solaris 9 and later
Multithreading Models
▪ Many-to-One
✓ Many user-level threads
mapped to a single kernel
thread
✓ Examples:
✓ Solaris Green Threads
✓ GNU Portable Threads
Concurrency
• Concurrency is the execution of a set of multiple
instruction sequences at the same time.

• running a lot of programs concurrently (the O.S. has to


multiplex their execution on available processors).

• For example: downloading a file.

listening to streaming audio.


Principles of Concurrency :
▪ Both interleaved and overlapped processes can be viewed as examples of
concurrent processes, both present the same problems.

▪ The relative speed of execution cannot be predicted. It depends on the


following:
✓ The activities of other processes

✓ The way operating system handles interrupts

✓ The scheduling policies of the operating system


❑ Problems in Concurrency ❑ Concurrency arises in three

• Sharing global resources different contexts:


✓ Multiple applications
• Optimal allocation of resources
✓ Structured applications
• Locating programming errors
✓ Operating system structure
• Locking the channel
Concurrency: Mutual Exclusion
and Synchronization
The central themes of operating system design are all concerned with the
management of processes and threads.
• Multiprogramming: The management of multiple processes within a
uni-processor system.
• Multiprocessing: The management of multiple processes within a
multiprocessor.
• Distributed processing: The management of multiple processes
executing on multiple, distributed computer systems.
• Semaphore is an object that consists of a counter, a waiting list of
processes and two methods : signal and wait.

70
71
Concurrency …
• In the case of competing processes three control problems must be faced.

• First is the need for mutual exclusion.

• Suppose two or more processes require access to a single non-sharable

resource, such as a printer.

• During the course of execution, each process will be sending commands

to the I/O device, receiving status information, sending data, and/or

receiving data.
72
For process scheduling operating system uses:

First Come First Serve (FCFS) Algorithm: which comes first is served first by
the CPU until it is completed. It is a non-preemptive algorithm which means it
cannot be terminated without completing it.
Shortest Job First (SJF) Algorithm: The process which has the shortest burst
time (execution time) that will be served first by the CPU.
Longest Job First (LJF) Algorithm: This algorithm is based on the
phenomenon that the process that has the longest execution time will be served
first by the processor.
For process scheduling operating system uses:
Round Robin Algorithm: In this algorithm, there is a specific time
quanta assigned for each process. If the process is not executed in
time quanta, it is sent to the waiting queue for its next turn.
Priority Scheduling Algorithm: Processes are given the priority
based on different criteria and scheduled according to the highest
priority. Criteria can be burst time or arrival time etc.
Basic process and thread management in:
- Linux-creating
- Linux-monitoring
- Linux-killing processes
- Threads in Linux
Linux Process and Thread Management
▪A process in LINUX is a single program running in its own virtual
space on the operating system.
▪To create a process in LINUX, the ‘parent process‘ initiate a fork().
▪Fork() suggests that the process creates a copy of itself.
▪A process in LINUX is represented by a data structure (like PCB) is
called ‘task-struct‘.
▪It contains the all information about the process.
LINUX Task Structure:
1. PID It specifies one of the 5 states of a process.
3. Scheduling Information: It specifies that which type of information needed.
4. Links: Process having the link to its parent process if it is a child process.
If it is a parent process links to all of its children.
5. File System: It includes pointers to any files opened by this process.
6. Virtual Memory: It defines the virtual memory assigned to this process.
7. Times and Timers: It specifies process creation time, CPU burst time of a process, etc.
8. Processor-specific context: The registers and stack information that constitute the
context of this process.
Process creation in Linux
Linux system call for creating process and thread
System calls
- write (), open(), dup(), read()
Process
- fork(), wait(), system(),
Thread, deadlock,
synchronization
- Mutex-lock
- semaphores
IPC – pipe(), popen()/pclose(), mkfifo(),and shared memory
Process in Linux
• A process is a computer program under execution, so, Linux is
running many processes at any given time.
• We can monitor them on the terminal using the ps command or on
the system monitor UI.
• For instance, let’s see an example of using the ps command to view
all the processes running on the machine:
ps –ef
• Linux processes are isolated and do not interrupt each other’s
execution.
• With a PID, we can identify any process in Linux.
Process in Linux
• Type the ps aux to see all running process in Linux.
• ps command is short for ‘Process Status’ PID
• PID - process ID
• TTY - terminal type
• TIME - total time the process has been running
• CMD - name of the command that launches the process
• To get more information using ps command use: ps -u
✓ CPU represents the amount of computing power the process is taking.
✓ MEM represents the amount of memory the process is taking up.
✓ STAT represents process state.
▪ While ps command only displays the processes that are currently
running, you can also use it to list all the processes. ps – A

Stop a process: Kill –L ; ‘kill -9’ which is ‘SIGKILL’.


▪ The syntax for killing a process is: kill [pid]
▪ Alternatively you can also use: kill -9 [pid]
➢ To start a process and give it a nice value other than the default
one, use: nice -n [value] [process name]
➢ To change nice value of a process that is already running use:
renice [value] -p 'PID'
To display info about processes on Linux operating systems:
top command: Display and update sorted information about Linux
processes.
atop command: Advanced System & Process Monitor for Linux.
htop command: Interactive process viewer in Linux.
pgrep command: Look up or signal processes based on name and
other attributes.
pstree command: Display a tree of processes.
How to list process with the ps command
Type the following ps command to display all running process:
ps -aux | less
OR filter ps command outputs using the less command:
ps aux | less
To negates the selection pass the -N or --
deselect option to the ps command:
# ps -U root -u root -N
OR
# ps -U root -u root --deselect
See every process on the Linux system
▪Either pass -A or -e option to show all processes on your
server/workstation powered by Linux:
ps –A or ps –e
▪How to see every process except those running as root?
To negates the selection pass the -N or --deselect option to
the ps command:
ps -U root -u root –N or
ps -U root -u root –deselect
Linux running processes with top command
The top program provides a dynamic real-time view of a running
system. Type the top at command prompt:
# top
How to display a tree of processes
# Pstree
Print a process tree using ps
# ps -ejH
# ps axjf
Get info about threads
# ps –elf # ps axms
Get security info about running Linux process
ps -eo euser,ruser,suser,fuser,f,comm,label
# ps axZ # ps -eM
How to save process snapshot to a file
top -b -n1 > /tmp/process.log

You might also like