operating system concepts

116
Introduction To Operating Introduction To Operating System System

Upload: vivek278

Post on 23-Oct-2014

296 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Operating System Concepts

Introduction To Operating Introduction To Operating SystemSystem

Page 2: Operating System Concepts

Computer System

Hardware Software User

Input Units

CPU Output Units

Secondary storage

Processor

Memory

Control Unit

RAM Cache Memory

ROM

Magnetic Tapes

Magnetic Disks

Compact Disks

Floppy Disks

Hard Disks

Operating System

ApplicationPrograms

Compilers & Assemblers

Programming Languages

High Level

LowLevel

Page 3: Operating System Concepts

Q: Explain what is meant by “Application Programs”? Q: Explain what is meant by “Application Programs”?

Sol:Sol:

Hardware

Operating System

Application Programs

UserUser

SoftwareSoftware

Are programs produced by programming companies to help computer Are programs produced by programming companies to help computer users to perform useful tasks. users to perform useful tasks.

Application programs

Page 4: Operating System Concepts

Q: Draw a block diagram showing the computer internal Q: Draw a block diagram showing the computer internal structure. structure.

Sol:Sol:

Input Units

Output Units

Memory

(RAM)

Control Unit

Processor

Cache Cache MemoryMemory

ALUALU

ROM CPU

Instructions

Data

Instructions

Control Signals

Data

Results

Results

Secondary Storage

Store Results

Or

Load date

Page 5: Operating System Concepts

Q: Define the following:Q: Define the following:RAM – ROM – Cache Memory RAM – ROM – Cache Memory

Sol:Sol:

RAM:• Random Access Memory• Volatile (lose contents when power is off).• Can be modified by the user.

ROM:• Read only Memory• Non Volatile.• Contains fixed programs used by the computer.

Cache Memory:• A memory inside the processor chip. • Used to store frequently used data. • Increases the processor speed.

ProcessorProcessor

Cache Memor

yALU

Page 6: Operating System Concepts

Q: Write short notes about:Q: Write short notes about:““Secondary Storage Units”Secondary Storage Units”

Sol:Sol:

Definition:• Secondary storage units are the units used to store data

permanently.

Secondary Secondary StorageStorage

Magnetic DisksMagnetic Disks Magnetic TapesMagnetic Tapes Compact DisksCompact Disks

Floppy DisksFloppy Disks Hard DisksHard Disks

Page 7: Operating System Concepts

Magnetic Tapes:

Used to store large volume of data in large computers like mainframes for long time.

Consists of plastic film coated by magnetic material (iron oxide).

– Advantages: Advantages: • Compact (can store huge amount of data).Compact (can store huge amount of data).• Economical (low cost).Economical (low cost).• No loss of data.No loss of data.

– Disadvantages: Disadvantages: • Sequential storage.Sequential storage.

Page 8: Operating System Concepts

Magnetic Disks:Magnetic Disks:

A surface of metal (in the case of hard disk) A surface of metal (in the case of hard disk) or plastic (in floppy disks) coated with or plastic (in floppy disks) coated with magnetic material. magnetic material.

It rotates with a high speed.It rotates with a high speed. Divided into tracks and sectors. Divided into tracks and sectors. TrackTrack

SectorSector

Page 9: Operating System Concepts

Compact Disks:Compact Disks:

CD/ROM (Compact Disk/Read Only Memory).CD/ROM (Compact Disk/Read Only Memory). A plastic surface coated by a reflective A plastic surface coated by a reflective

material.material. A laser beam is used to write on CD/ROM.A laser beam is used to write on CD/ROM. Can store up to 600 Mega byte. Can store up to 600 Mega byte.

Page 10: Operating System Concepts

Q: Define OS, then what are the different OS goals?Q: Define OS, then what are the different OS goals?Sol:Sol:

Operating System (OS): Operating System (OS):

– is the program running all the times on the computer to is the program running all the times on the computer to communicate all computer components (usually called communicate all computer components (usually called Kernel).Kernel).

– OS does not perform a useful task by itself, but it creates a OS does not perform a useful task by itself, but it creates a suitable environment so that other programs can operate suitable environment so that other programs can operate efficiently. efficiently.

OS Goals:

• Convenient for the user.• Efficient for the system components.

Page 11: Operating System Concepts

Q: What are the different types of OS?Q: What are the different types of OS?Sol:Sol:

Different Types of OS are:Different Types of OS are:

1.1. Batch System.Batch System.

2.2. Multi-Programming System.Multi-Programming System.

3.3. Multi-Tasking (Time Sharing) Multi-Tasking (Time Sharing) System.System.

4.4. Multi-Processor (Parallel) System.Multi-Processor (Parallel) System.

5.5. Network Operating Systems.Network Operating Systems.

6.6. Real Time Systems. Real Time Systems.

Page 12: Operating System Concepts

Batch System: Batch System:

• Users send their jobs to the computer operator.Users send their jobs to the computer operator.

• Operator organize jobs into a set of batches (each contains similar Operator organize jobs into a set of batches (each contains similar jobs).jobs).

• Each batch is run separately as a set of jobs. Each batch is run separately as a set of jobs.

CPU

Batch 1Batch 1

Batch 1Batch 1

Batch 2Batch 2

Job

Operator

Next batch

Page 13: Operating System Concepts

Multi-Programming System: Multi-Programming System:

• A number of processes are in memory inside the ready queue A number of processes are in memory inside the ready queue waiting for the CPU (there is one user).waiting for the CPU (there is one user).

• Windows OS using this concept. Windows OS using this concept.

MemoryMemory

CPUCPU

Process 1Process 1

Process 2Process 2

Process 3Process 3

Ready Ready QueueQueue

Switching between Switching between processesprocesses

Page 14: Operating System Concepts

Multi-Tasking (Time sharing) System: Multi-Tasking (Time sharing) System:

• Allow a number of users to share the CPU in the same time.Allow a number of users to share the CPU in the same time.

• This concepts is used in the mainframe computers. This concepts is used in the mainframe computers.

CPUCPU

Switching between Switching between users processesusers processes

User 1

MemoryMemory

Process 1Process 1

Process 2Process 2

Process 3Process 3

Ready Queue for user 1Ready Queue for user 1

User 2

User 3

Process 1Process 1

Process 2Process 2

Process 3Process 3

Ready Queue for user 2Ready Queue for user 2

Process 1Process 1

Process 2Process 2

Process 3Process 3

Ready Queue for user 3Ready Queue for user 3

Page 15: Operating System Concepts

Multi-Processor System: Multi-Processor System:

• Is a system with more than one processor to maximize the system Is a system with more than one processor to maximize the system speed. speed.

MemoryMemory

CPU 2CPU 2

CPU 1CPU 1

CPU 3CPU 3

User

Process 1Process 1

Process 2Process 2

Process 3Process 3

Ready QueueReady Queue

Page 16: Operating System Concepts

Network System: Network System:

• Systems that operate networks in order to achieve:Systems that operate networks in order to achieve:

Resource sharing.Resource sharing. Computation speedup.Computation speedup. Load balancing.Load balancing. Communication between hosts. Communication between hosts.

Star

Ring

Bus

Page 17: Operating System Concepts

Real Time System: Real Time System:

• Systems that performs critical tasks.Systems that performs critical tasks.

Real Time Real Time SystemsSystems

Hard Real Time SystemsHard Real Time Systems Soft Real Time SystemsSoft Real Time Systems

• Hard real time systems: critical tasks must be performed Hard real time systems: critical tasks must be performed on time.on time.

• Soft real time systems: critical tasks gets priority over Soft real time systems: critical tasks gets priority over other tasks. other tasks.

Page 18: Operating System Concepts

Q: What are the different activates supported by modern OS?Q: What are the different activates supported by modern OS?

Sol:Sol:

Different OS functions are:Different OS functions are:

1.1. Process Management.Process Management.

2.2. Memory Management.Memory Management.

3.3. File Management.File Management.

4.4. Storage Management.Storage Management.

5.5. I/O Management.I/O Management.

6.6. Protection Management.Protection Management.

7.7. Networking Management. Networking Management.

Page 19: Operating System Concepts

ProcessProcess

ManagementManagementProcessProcess

ManagementManagement

Page 20: Operating System Concepts

Q: Define the following:Q: Define the following:Process – ResourceProcess – Resource

Sol:Sol:ProcessProcess: : is a program in execution; it is an active entity in the memory is a program in execution; it is an active entity in the memory while the program is the passive copy in the hard disk.while the program is the passive copy in the hard disk.

Resource:Resource: any things in the system that may be used by active any things in the system that may be used by active processes. They may be hardware (printers, tape drives, memory), or processes. They may be hardware (printers, tape drives, memory), or software (files, databases). software (files, databases).

Program Program

Process 1Process 1

Process 2Process 2Hard Hard

DiskDisk

MemoryMemory

Page 21: Operating System Concepts

Resource TypesResource TypesResource TypesResource Types

Preemptive Preemptive Resources Resources

االولوية على يعتمد االولوية مصدر على يعتمد مصدر

A resource that stops the current A resource that stops the current process when a higher priority process when a higher priority

process comes. process comes.

Ex: Memory.Ex: Memory.

Non PreemptiveNon Preemptive ResourcesResources

االولوية على يعتمد ال االولوية مصدر على يعتمد ال مصدر

A resource that can not stop the current A resource that can not stop the current process when a higher priority process process when a higher priority process

comes. comes.

Ex: CD recorder,Ex: CD recorder,

Page 22: Operating System Concepts

Q: Explain why? Memory is a preemptive recourse.Q: Explain why? Memory is a preemptive recourse.

Sol:Sol:

Because Because

It allows a low priority process to swapped It allows a low priority process to swapped out form it to the disk when a higher out form it to the disk when a higher

priority process arrives and needs a larger priority process arrives and needs a larger amount of memory than the available. The amount of memory than the available. The low priority process can resume execution low priority process can resume execution

later (swapped in again). later (swapped in again).

Page 23: Operating System Concepts

• Assume a system with 32 kb memory size.Assume a system with 32 kb memory size.

• 5kb are used for OS, 10 kb for the low priority process.5kb are used for OS, 10 kb for the low priority process.

• Hence, the available space is 17 kb. Hence, the available space is 17 kb.

• A higher priority process arrives and needs 20 kb. A higher priority process arrives and needs 20 kb.

OS (5 kb)OS (5 kb)

Low Priority Low Priority process (10 process (10

kb)kb)

Available Available 17 Kb17 Kb

OS (5 kb)OS (5 kb)

Available Available 27 Kb27 Kb

OS (5 kb)OS (5 kb)

High Priority High Priority process (20 process (20

kb)kb)

Available Available 7 Kb7 Kb

OS (5 kb)OS (5 kb)

Available Available 27 Kb27 Kb

SwapSwap in the highin the high

priority processpriority processhigh priority process high priority process

finishes executionfinishes execution

Swap out the low Swap out the low priority process to priority process to

diskdisk

DiskDisk

Swap in the low priority process again toSwap in the low priority process again to

resume executionresume execution

High High PriorityPriority 20 Kb20 Kb

Page 24: Operating System Concepts

Q: Explain why? CD recorder is nonpreemptive resource.Q: Explain why? CD recorder is nonpreemptive resource.

Sol:Sol:

Because:Because: If a process has begun to burn a CD-If a process has begun to burn a CD-ROM, suddenly taking the CD recorder away ROM, suddenly taking the CD recorder away from it and giving it to another process will from it and giving it to another process will result in a bad CD.result in a bad CD.

Page 25: Operating System Concepts

Q: What are the different steps to utilize a Q: What are the different steps to utilize a resource by a process? resource by a process? Sol:Sol:

A process may utilize a resource in only the A process may utilize a resource in only the following sequence as shown below:following sequence as shown below:

RequesRequestt

UseUse

ReleasReleasee

Page 26: Operating System Concepts

Q: Explain the main differences between a input Q: Explain the main differences between a input (job) and ready queues?(job) and ready queues?

Sol:Sol:--input queue:input queue: stores the programs that will be opened soon ( stores the programs that will be opened soon (located located at the diskat the disk))

- - ready queue:ready queue: contains the active process that are ready to be contains the active process that are ready to be executed (executed (located in the memorylocated in the memory).).

Ready Queue

Process need to be executed (programs)

Page 27: Operating System Concepts

Q: Explain what is meant by process states, and then Q: Explain what is meant by process states, and then draw the process state diagram. draw the process state diagram.

SolSol::

As process executes, it changes its state. The process state may be:As process executes, it changes its state. The process state may be:

• New:New: The process is being created.The process is being created.

• Ready:Ready: The process is waiting for the processor. The process is waiting for the processor.

• Running:Running: The process instructions are being executed. The process instructions are being executed.

• Waiting:Waiting: The process is waiting for an event to happen The process is waiting for an event to happen (such as I/O completion). (such as I/O completion).

• Terminated:Terminated: The process has finished execution.The process has finished execution.

Page 28: Operating System Concepts

The process state diagram is:The process state diagram is:

Dispatcher

Page 29: Operating System Concepts

Q: Explain why? Each process must have a process Q: Explain why? Each process must have a process control block (PCB) in memory. control block (PCB) in memory.

Sol:Sol:

Because: Because:

• Process control block (PCB) is the way used to Process control block (PCB) is the way used to represent the process in the operating system. represent the process in the operating system.

• بالعملية الخاصة المعلومات جميع لتخزين بالعملية يستخدم الخاصة المعلومات جميع لتخزين يستخدمالعملية متابعة التشغيل نظام يستطيع العملية حتى متابعة التشغيل نظام يستطيع حتى

• It contains information about the process such It contains information about the process such as:as:– Process stateProcess state (new, ready, …)(new, ready, …)

– Address of the next instructionAddress of the next instruction to be executed to be executed in the process.in the process.

– Process priority.Process priority.

– Process assigned memory.Process assigned memory.

– I/O informationI/O information (such as I/O devices and (such as I/O devices and opened files). opened files).

Page 30: Operating System Concepts

Q: Show graphically how OS uses the PCB to switch between active Q: Show graphically how OS uses the PCB to switch between active processesprocesses

Sol:Sol:

• When interrupt happenedWhen interrupt happened, OS saves the state of the current active process to , OS saves the state of the current active process to its PCB so it can continue correctly when it resumes its execution again.its PCB so it can continue correctly when it resumes its execution again.

• To resume execution,To resume execution, OS reloads the process state from its PCB and continue OS reloads the process state from its PCB and continue execution. execution.

Page 31: Operating System Concepts

Q: Give a suitable definition for the "Context Q: Give a suitable definition for the "Context Switch", and then explain why context switch is Switch", and then explain why context switch is a pure overhead? a pure overhead?

Sol:Sol:Context switchContext switch is the time needed by OS to is the time needed by OS to

switch the processor from a process to another.switch the processor from a process to another.

اخرى الى عملية من لالنتقال المستغرق الوقت اخرى هو الى عملية من لالنتقال المستغرق الوقت هو

Context switch(PContext switch(Pxx PPyy)) = T= TXX + T + TYY , where , whereTTXX : time needed to save the state of P : time needed to save the state of Pxx in PCB in PCBxx

TTYY : time needed to load the state of P : time needed to load the state of PYY in PCB in PCBYY

Context switchContext switch is a pure overhead because the is a pure overhead because the system does no useful work while switching. system does no useful work while switching.

Page 32: Operating System Concepts

Q: what is meant by Schedulers?, then discuss different Q: what is meant by Schedulers?, then discuss different types of them? types of them?

Sol:Sol:Long-term schedulerLong-term scheduler (or job scheduler) – selects which (or job scheduler) – selects which

processes should be brought into the ready queue from processes should be brought into the ready queue from the job queue (determine the degree of multi-the job queue (determine the degree of multi-programming)programming)

Short-term schedulerShort-term scheduler (or CPU scheduler) – selects (or CPU scheduler) – selects which process should be executed next and allocates which process should be executed next and allocates CPUCPU

Medium-term schedulerMedium-term scheduler: swap out the process from : swap out the process from memory (ready queue) and swapped in again later (it memory (ready queue) and swapped in again later (it decrease the degree of multiprogramming). decrease the degree of multiprogramming).

Page 33: Operating System Concepts

Passive Passive ProgramsPrograms

Job (input) Job (input) QueueQueue

Long Term Long Term SchedulerScheduler

Open Open programprogram

Short Term Short Term SchedulerScheduler

CPUCPUCPUCPU

Medium Term Medium Term SchedulerScheduler

MemoryMemory

ProcessProcess

ProcessProcess

DiskDisk

Select a Select a process process

from job to from job to ready queueready queue

Swap a Swap a process process

from ready from ready to job queueto job queue

Assign the Assign the CPU to a CPU to a process process

from ready from ready queuequeue

Page 34: Operating System Concepts

Q: Explain why?Q: Explain why? Long term scheduler Long term scheduler increasesincreases the degree of the degree of

multiprogramming.multiprogramming. Medium term scheduler Medium term scheduler decreasesdecreases the degree of the degree of

multiprogramming. multiprogramming.

SolSol::• Degree of multi-programmingDegree of multi-programming is the number of is the number of processes that are placed in the ready queue waiting for processes that are placed in the ready queue waiting for execution by the CPU. execution by the CPU.

MemoryMemory

Process 4Process 4

Process 5Process 5

Process 3Process 3

Process 2Process 2

Process 1Process 1

Degree of Degree of

Multi-ProgrammingMulti-Programming

Page 35: Operating System Concepts

• Since Long term schedulerSince Long term scheduler selects which processes to selects which processes to brought to the ready queue, hence, it Decreases the brought to the ready queue, hence, it Decreases the degree of multiprogramming.degree of multiprogramming.

Degree of Degree of

Multi-ProgrammingMulti-Programming

Job QueueJob Queue

Long Term Long Term SchedulerScheduler

Degree of Degree of

Multi-ProgrammingMulti-Programming

MemoryMemory

Process 4Process 4

Process 5Process 5

Process 3Process 3

Process 2Process 2

Process 1Process 1

DiskDisk

Page 36: Operating System Concepts

Since Medium term schedulerSince Medium term scheduler picks some processes from picks some processes from the ready queue and swap them out of memory, hence, it the ready queue and swap them out of memory, hence, it decreases the degree of multiprogramming. decreases the degree of multiprogramming.

Degree of Degree of

Multi-ProgrammingMulti-Programming

Job QueueJob Queue

Medium Medium Term Term

SchedulerSchedulerDegree of Degree of

Multi-ProgrammingMulti-Programming

MemoryMemory

Process 4Process 4

Process 5Process 5

Process 3Process 3

Process 2Process 2

Process 1Process 1

DiskDisk

Page 37: Operating System Concepts

((Ready QueueReady Queue)) ((Ready QueueReady Queue))

CPU CPU SchedulingScheduling

Page 38: Operating System Concepts

Q: Explain what is meant by CPU scheduling, and Q: Explain what is meant by CPU scheduling, and then discuss the difference between loader and then discuss the difference between loader and dispatcher? dispatcher?

Sol:Sol:

Difference between loader and dispatcher:Difference between loader and dispatcher:Ready Queue

Process need to be executed

Page 39: Operating System Concepts

MemoryMemory

CPU schedulingCPU schedulingCPU Scheduling is the method to CPU Scheduling is the method to selectselect a a

process from the ready queue to be executed by process from the ready queue to be executed by CPU when ever the CPU becomes CPU when ever the CPU becomes idleidle. .

Some Examples:Some Examples:First Come First Serviced (First Come First Serviced (FCFSFCFS) scheduling.) scheduling.Shortest Job First (Shortest Job First (SJFSJF) scheduling.) scheduling.Priority scheduling.Priority scheduling.

CPUCPU

Process 1Process 1

Process 2Process 2

Process 3Process 3

Ready Ready QueueQueue DispatcherDispatcher??

CPU Scheduling CPU Scheduling AlgorithmAlgorithm

FCFSFCFS

SJFSJFPriorityPriority

Page 40: Operating System Concepts

Q: Explain the main differences between Q: Explain the main differences between preemptive and non preemptive scheduling? preemptive and non preemptive scheduling?

Sol:Sol:

Preemptive scheduling:Preemptive scheduling: allows releasing the allows releasing the current executing process from CPU when current executing process from CPU when another process (another process (which has a higher prioritywhich has a higher priority) ) comes and need execution.comes and need execution.

Non-preemptive schedulingNon-preemptive scheduling: once the CPU has : once the CPU has been allocated to a process, the process keeps been allocated to a process, the process keeps the CPU until it release the CPU . the CPU until it release the CPU .

Page 41: Operating System Concepts

CPUCPU

CPUCPU

Preemptive Preemptive SchedulingScheduling

Non- Preemptive Non- Preemptive SchedulingScheduling

Page 42: Operating System Concepts

Q: discuss in details, what is meant by the Q: discuss in details, what is meant by the following parameters:following parameters:

CPU utilization.CPU utilization.System throughput.System throughput.Turnaround time.Turnaround time.Waiting time.Waiting time.Response time. Response time.

Then discuss which parameter to Then discuss which parameter to maximizemaximize and which one to and which one to minimizeminimize? ?

Page 43: Operating System Concepts

Sol:Sol:

CPU Utilization:CPU Utilization:

The The percentagepercentage of of times while CPU is busytimes while CPU is busy to the to the total timetotal time ( times CPU busy + times it is idle). ( times CPU busy + times it is idle). Hence, it measures the benefits from CPU.Hence, it measures the benefits from CPU.

To maximize utilization, To maximize utilization, keep CPU as busy as keep CPU as busy as possible. possible.

CPU utilization range from CPU utilization range from 40%40% (for lightly loaded (for lightly loaded systems) to systems) to 90%90% (for heavily loaded) ( (for heavily loaded) (Explain why? Explain why? CPU utilization can not reach 100%,CPU utilization can not reach 100%, because of the because of the context switch between active processes). context switch between active processes).

100*TimeTotal

BusyCPUTimesnUtilizatioCPU

Page 44: Operating System Concepts

System Throughput:System Throughput: The number of process that are completed per time unit The number of process that are completed per time unit

((hourhour))

Turnaround time: Turnaround time: For a particular process, it is the total time needed for For a particular process, it is the total time needed for

process execution (process execution (from the time of submission to the from the time of submission to the time of completiontime of completion). ).

It is the sum of process It is the sum of process executionexecution time and its time and its waiting waiting timestimes (to get memory, perform I/O, ….). (to get memory, perform I/O, ….).

Waiting time: Waiting time: The waiting time for a specific process is the sum of all The waiting time for a specific process is the sum of all

periods it spends waiting in the ready queue.periods it spends waiting in the ready queue.

Response time.Response time. It is the time from the It is the time from the submissionsubmission of a process until the of a process until the

first responsefirst response is produced ( is produced (the time the process takes to the time the process takes to start respondingstart responding). ).

Page 45: Operating System Concepts

It is desirable to:It is desirable to:

Maximize: Maximize: CPU utilization.CPU utilization.System throughput.System throughput.

Minimize:Minimize:Turnaround time.Turnaround time.Waiting time.Waiting time.Response time.Response time.

Page 46: Operating System Concepts

First Come First Serviced (FCFS) algorithmFirst Come First Serviced (FCFS) algorithm

The process that comes first will be The process that comes first will be executed first.executed first.

Not preemptive.Not preemptive.

CPUCPU

FCFS SchedulingFCFS Scheduling

Ready queueReady queue

Page 47: Operating System Concepts

Consider the following set of processes, with the length of Consider the following set of processes, with the length of the CPU burst (the CPU burst (ExecutionExecution) time given in ) time given in millisecondsmilliseconds::

The processes arrive in the order The processes arrive in the order P1, P2, P3. All at time 0.P1, P2, P3. All at time 0.

Gant chart:Gant chart:

waiting times and turnaround times for each process waiting times and turnaround times for each process are:are:

Hence, average waiting time= Hence, average waiting time= (0+24+27)/3=17(0+24+27)/3=17 milliseconds milliseconds

ProcessProcess Burst TimeBurst Time

P1P1 2424

P2P2 33

P3P3 33

ProcessProcess P1P1 P2P2 P3P3

Waiting Time (WT)Waiting Time (WT) 00 2424 2727

Turnaround Time (TAT)Turnaround Time (TAT) 2424 2727 3030++

Execution Execution TimeTime

1111

33332222

Page 48: Operating System Concepts

Repeat the previous example, assuming that the Repeat the previous example, assuming that the processes arrive in the order processes arrive in the order P2, P3, P1P2, P3, P1. All at time 0. . All at time 0.

Gant chart:Gant chart:

waiting times and turnaround times for each process waiting times and turnaround times for each process are:are:

Hence, average waiting time= Hence, average waiting time= (6+0+3)/3=3(6+0+3)/3=3 milliseconds milliseconds

ProcessProcess Burst TimeBurst Time

P1P1 2424

P2P2 33

P3P3 33

ProcessProcess P1P1 P2P2 P3P3

Waiting Time (WT)Waiting Time (WT) 66 00 33

Turnaround Time (TAT)Turnaround Time (TAT) 3030 33 66

1111

2222

3333

Page 49: Operating System Concepts

Q: Q: Explain why?Explain why? FCFS CPU scheduling FCFS CPU scheduling algorithm introduces a long average algorithm introduces a long average waiting time? waiting time?

Sol:Sol:

Because:Because: it suffers from it suffers from Convoy effectConvoy effect, hence, all other , hence, all other

processes must wait for the big process to execute processes must wait for the big process to execute if this big process comes first. if this big process comes first.

This results in a long waiting time for small This results in a long waiting time for small processesprocesses, and accordingly increases the average , and accordingly increases the average waiting time. waiting time.

Page 50: Operating System Concepts

Shortest-Job-First (SJF) schedulingShortest-Job-First (SJF) scheduling

When CPU is available, it will be assigned to When CPU is available, it will be assigned to the process with the smallest CPU burst (the process with the smallest CPU burst (non non

preemptivepreemptive). ). If two processes have the same next CPU If two processes have the same next CPU

burst, burst, FCFSFCFS is used. is used.

CPUCPU

55

SJF SchedulingSJF Scheduling

1818 771010

55771010

X1818

Note: Note: numbers indicates the process execution timenumbers indicates the process execution time

Page 51: Operating System Concepts

Consider the following set of processes, with the length of Consider the following set of processes, with the length of the CPU burst time given in the CPU burst time given in millisecondsmilliseconds::

The processes arrive in the order The processes arrive in the order P1, P2, P3, P4. All at time 0.P1, P2, P3, P4. All at time 0.

1. 1. Using FCFSUsing FCFS Gant chart:Gant chart:

waiting times and turnaround times for each process waiting times and turnaround times for each process are:are:

Hence, Hence, average waiting timeaverage waiting time= (0+6+14+21)/4== (0+6+14+21)/4=10.25 10.25 milliseconds milliseconds

ProcessProcess Burst TimeBurst Time

P1P1 66

P2P2 88

P3P3 77

P4P4 33

ProcessProcess P1P1 P2P2 P3P3 P4P4

Waiting Time (WT)Waiting Time (WT) 00 66 1414 2121

Turnaround Time (TAT)Turnaround Time (TAT) 66 1414 2121 2424

Page 52: Operating System Concepts

2. Using SJF2. Using SJF

Gant chart:Gant chart:

waiting times and turnaround times for each process waiting times and turnaround times for each process are:are:

Hence, average waiting time= (3+16+9+0)/4=7 Hence, average waiting time= (3+16+9+0)/4=7 milliseconds milliseconds

ProcessProcess Burst TimeBurst Time

P1P1 66

P2P2 88

P3P3 77

P4P4 33

ProcessProcess P1P1 P2P2 P3P3 P4P4

Waiting Time (WT)Waiting Time (WT) 33 1616 99 00

Turnaround Time (TAT)Turnaround Time (TAT) 99 2424 1616 33

Page 53: Operating System Concepts

Q: Explain why? SJF CPU scheduling algorithm introduces the Q: Explain why? SJF CPU scheduling algorithm introduces the minimum average waiting time for a set of processes? Give an minimum average waiting time for a set of processes? Give an example. example.

Sol:Sol:

Because: by Because: by moving a short process before a long onemoving a short process before a long one, the waiting , the waiting time of the short process decreases more than it increases the time of the short process decreases more than it increases the waiting time of the long process. Hence, the average waiting waiting time of the long process. Hence, the average waiting time decreasestime decreases.

Example: assuming two processes P1 and P2Example: assuming two processes P1 and P2

ProcessProcess Burst TimeBurst Time

P1P1 3030

P2P2 22

P1 P2

0 30 32Waiting time(P1)=0Waiting time(P1)=0

Waiting time(P2)=30Waiting time(P2)=30

Average waiting time=(0+30)/2=15Average waiting time=(0+30)/2=15

P1P2

0 2 32

Waiting time(P1)=2Waiting time(P1)=2

Waiting time(P2)=0Waiting time(P2)=0

Average waiting time=(0+2)/2=1Average waiting time=(0+2)/2=1

Using FCFSUsing FCFS Using SJFUsing SJF

Page 54: Operating System Concepts

Shortest-Remaining-Time-First (SRTF)Shortest-Remaining-Time-First (SRTF)

It is a It is a preemptive versionpreemptive version of the Shortest Job of the Shortest Job First .First .

It allows a new process to gain the processor It allows a new process to gain the processor if its execution time less than the remaining if its execution time less than the remaining time of the currently processing one.time of the currently processing one.

CPUCPU

SRTF SchedulingSRTF Scheduling

5577101022 4433

Page 55: Operating System Concepts

Consider the following set of processes, with the length of Consider the following set of processes, with the length of the CPU burst time given in milliseconds:the CPU burst time given in milliseconds:

The processes arrive in the order The processes arrive in the order P1, P2, P3, P4P1, P2, P3, P4. as shown in table. . as shown in table.

1. Using SJF1. Using SJF Gant chart:Gant chart:

waiting times and turnaround times for each process waiting times and turnaround times for each process are:are:

Hence, Hence, average waiting timeaverage waiting time= (0+6+3+7)/4== (0+6+3+7)/4=44 milliseconds milliseconds

ProcessProcess Burst TimeBurst Time Arrival TimeArrival Time

P1P1 77 00

P2P2 44 22

P3P3 11 44

P4P4 44 55

ProcessProcess P1P1 P2P2 P3P3 P4P4

Waiting Time (WT)Waiting Time (WT) 00 66 33 77

Turnaround Time (TAT)Turnaround Time (TAT) 77 1010 44 1111

Page 56: Operating System Concepts

2. Using SRTF2. Using SRTF

Gant chart:Gant chart:

waiting times and turnaround times for each process waiting times and turnaround times for each process are:are:

Hence, Hence, average waiting timeaverage waiting time= (9+1+0+2)/4=3 = (9+1+0+2)/4=3 milliseconds milliseconds

ProcessProcess P1P1 P2P2 P3P3 P4P4

Waiting Time (WT)Waiting Time (WT) 99 11 00 22

Turnaround Time (TAT)Turnaround Time (TAT) 1616 55 11 66

ProcessProcess Burst TimeBurst Time Arrival TimeArrival Time

P1P1 77 00

P2P2 44 22

P3P3 11 44

P4P4 44 55

Page 57: Operating System Concepts

Priority schedulingPriority scheduling A priority numberA priority number (integer) is associated (integer) is associated

with each processwith each process The CPU is allocated to the process with the The CPU is allocated to the process with the

highest priority (smallest integer). There are highest priority (smallest integer). There are two types:two types:

PreemptivePreemptive nonpreemptivenonpreemptive

CPUCPU

55

Priority SchedulingPriority Scheduling

1818 771010

55771010

X1818

Note: Note: numbers indicates the process prioritynumbers indicates the process priority

Page 58: Operating System Concepts

Problems with Priority scheduling Problems with Priority scheduling

Problem Problem StarvationStarvation (infinite blocking)– low (infinite blocking)– low priority processes may never executepriority processes may never execute

Solution Solution AgingAging – as time progresses – as time progresses increase the priority of the processincrease the priority of the process

55 44 223030

Very low priority processVery low priority process

88 882828

Very low priority processVery low priority process

2626

Very low priority processVery low priority process

StarvationStarvationAgingAging

Page 59: Operating System Concepts

Consider the following set of processes, with the length of Consider the following set of processes, with the length of the CPU burst time given in milliseconds:the CPU burst time given in milliseconds:

The processes arrive in the order The processes arrive in the order P1, P2, P3, P4, P5. All at time 0P1, P2, P3, P4, P5. All at time 0. .

1. Using priority scheduling1. Using priority scheduling Gant chart:Gant chart:

waiting times and turnaround times for each process waiting times and turnaround times for each process are:are:

Hence, Hence, average waiting timeaverage waiting time= (6+0+16+18+1)/5=8.2 = (6+0+16+18+1)/5=8.2 milliseconds milliseconds

ProcessProcess Burst TimeBurst Time prioritypriority

P1P1 1010 33

P2P2 11 11

P3P3 22 44

P4P4 11 55

P5P5 55 22

ProcessProcess P1P1 P2P2 P3P3 P4P4 P5P5

Waiting Time (WT)Waiting Time (WT) 66 00 1616 1818 11

Turnaround Time (TAT)Turnaround Time (TAT) 1616 11 1818 1919 66

Page 60: Operating System Concepts

Round Robin schedulingRound Robin scheduling Allocate the CPU for one Allocate the CPU for one Quantum timeQuantum time ( (also also

called time slicecalled time slice) ) QQ to each process in the to each process in the ready queue.ready queue.

This scheme is repeated until all processes This scheme is repeated until all processes are finished.are finished.

A new process is added to the end of the A new process is added to the end of the ready queue.ready queue.

CPUCPU

Round Roben SchedulingRound Roben Scheduling

QQQQQQ

QQ

CPUCPU

QQQQQQ

QQ

CPUCPU

QQQQQQ

QQ

CPUCPU

QQQQQQ

QQ

Page 61: Operating System Concepts

Consider the following set of processes, with the length of the Consider the following set of processes, with the length of the CPU burst time given in milliseconds:CPU burst time given in milliseconds:

The processes arrive in the order The processes arrive in the order P1, P2, P3. All at time 0. P1, P2, P3. All at time 0. use RR scheduling with use RR scheduling with Q=2Q=2 and and Q=4Q=4

RR with Q=4RR with Q=4

Gant chart:Gant chart:

waiting times and turnaround times for each process are:waiting times and turnaround times for each process are:

Hence, Hence, average waiting timeaverage waiting time= (6+4+7)/3=5.66 milliseconds = (6+4+7)/3=5.66 milliseconds

ProcessProcess Burst TimeBurst Time

P1P1 2424

P2P2 33

P3P3 33

ProcessProcess P1P1 P2P2 P3P3

Waiting Time (WT)Waiting Time (WT) 66 44 77

Turnaround Time (TAT)Turnaround Time (TAT) 3030 77 1010

Page 62: Operating System Concepts

RR with Q=2RR with Q=2

Gant chart:Gant chart:

waiting times and turnaround times for each process waiting times and turnaround times for each process are:are:

Hence, average waiting time= (6+6+7)/3=6.33 Hence, average waiting time= (6+6+7)/3=6.33 milliseconds milliseconds

ProcessProcess Burst TimeBurst Time

P1P1 2424

P2P2 33

P3P3 33

ProcessProcess P1P1 P2P2 P3P3

Waiting Time (WT)Waiting Time (WT) 66 66 77

Turnaround Time (TAT)Turnaround Time (TAT) 3030 99 1010

Page 63: Operating System Concepts

Explain why? If the quantum time decrease, Explain why? If the quantum time decrease, this will slow down the execution of the this will slow down the execution of the processes.processes.

Sol:Sol:

Because decreasing the quantum time will Because decreasing the quantum time will increase the increase the context switchcontext switch ( (the time the time needed by the processor to switch between needed by the processor to switch between the processes in the ready queuethe processes in the ready queue) which will ) which will increase the time needed to finish the increase the time needed to finish the execution of the active processes, hence, execution of the active processes, hence, this slow down the system. this slow down the system.

Page 64: Operating System Concepts

Multi-level queuing schedulingMulti-level queuing scheduling There are two types:There are two types:

Without feedbackWithout feedback: processes can not move between : processes can not move between queues.queues.

With feedbackWith feedback: processes can move between queues. : processes can move between queues.

Multi-level queuing without feedback:Multi-level queuing without feedback:• Divide ready queue into several queues.Divide ready queue into several queues.• Each queue has specific priority and its own scheduling algorithm (FCFS, …).Each queue has specific priority and its own scheduling algorithm (FCFS, …).

High priority QueueHigh priority Queue

Low priority QueueLow priority Queue

Page 65: Operating System Concepts

Multi-level queuing with feedback:Multi-level queuing with feedback: Divide ready queue into several queues.Divide ready queue into several queues. Each queue has specific Quantum time as shown in Each queue has specific Quantum time as shown in

figure.figure. Allow processes to move between queues. Allow processes to move between queues.

Queue 1Queue 1

QueueQueue 00

Queue 2Queue 2

Page 66: Operating System Concepts

Deadlock

االقفال التام فى انظمة الحاسب االلى

Page 67: Operating System Concepts

Q: Give a suitable definition for the Deadlock problem. Q: Give a suitable definition for the Deadlock problem. Sol:Sol:

Solution:Solution:

A set of blocked processes, each:A set of blocked processes, each:

holding a resourceholding a resource

and waiting to use a resource held by another process in the set. and waiting to use a resource held by another process in the set.

1111

2222

Process BProcess BProcess AProcess A

Give me your recourse

Give me your recourse first

ResourceResource ResourceResource

Hence, blocked processes will never change state (Explain why?) because the resource it has requested is held by another waiting process.

Deadlock:دون التنفيذ عن دون متوقفة التنفيذ عن متوقفةرغبتهارغبتها

DeadlockDeadlock

Page 68: Operating System Concepts

DeadlockDeadlock

System BreakdownSystem Breakdown

Page 69: Operating System Concepts

Deadlock conditions

Hold andHold and waitwait

Mutual Mutual ExclusionExclusion

No preemptionNo preemption

Circular Circular waitwait

Q: Discuss briefly the different deadlock conditions. Q: Discuss briefly the different deadlock conditions. Sol:Sol:

Deadlock arises if four conditions hold simultaneously: Deadlock arises if four conditions hold simultaneously:

Page 70: Operating System Concepts

Mutual Exclusion

only one process can use a resource at a time.

111111

Hold and Wait

A process holding at least one resource is waiting for additional resource held by another processes

222222

Page 71: Operating System Concepts

No Preemption

A resource is released only by the process holding it after it completed its task

333333

Circular Wait

A set of processes each waits for another one in a circular fashion.

444444

Note: the four conditions must occur to have a deadlock. If one condition is

absent, a deadlock may not exist.

Page 72: Operating System Concepts

Circular Circular waitwait

•There exists a set {P0, P1, P2, ….., Pn} of waiting processes such that:

P0 waiting for a resource held by P1.

P1 waiting for a resource held by P2.

P2 waiting for a resource held by P3.

Pn waiting for a resource held by P0.

PP00

PP11

PP22

PP33

PP44

PPnn

Circular Circular WaitWait

Page 73: Operating System Concepts

Deadlock ModelingDeadlock Modeling (Resource Allocation Graph)(Resource Allocation Graph)

• In order to solve the deadlock problem, we must find a method to In order to solve the deadlock problem, we must find a method to express it. express it.

This can be achieved using resource allocation graph. This can be achieved using resource allocation graph.

Resource Allocation Graph

- All system - All system active processesactive processes..- Available - Available system resourcessystem resources . .- Interconnections between - Interconnections between active processesactive processes and and system resourcessystem resources. .

it is a graph expressing:it is a graph expressing:

مصادر توزيع يوضح شكل مصادر هو توزيع يوضح شكل هوالنشطة العمليات على النشطة النظام العمليات على النظام

Page 74: Operating System Concepts

ProcessProcess• P (Process Set) ≡ set of processes in the system

• P = {P1, P2, P3, ……., Pn}

ResourceResource• R (Resource Set) ≡ set of Resource types in the system

• R = {R1, R2, R3, ……., Rm}

EdgeEdge

• E (Edge Set) ≡ set of all edges in Resource Allocation Graph.

• E = {Pn Rm, Rx Py, …….. }

( Request edge )( Request edge )

Pi

Rj

( Assignment edge )( Assignment edge )

Pi

Rj

Process PProcess Pii requests an instance of requests an instance of

resource Rresource Rjj

An instance of Resource RAn instance of Resource Rj j is is

assigned to Process Passigned to Process Pii

Contents of Resource Allocation Graph

Page 75: Operating System Concepts

Example:Example:

Resource instances:

• One instance of R1 and R3.

• Two instances of R2.

• Three instances of R4.

Processes States: Processes States:

Process Holding Waiting

P1 Instance of R2 Instance of R1

P2 Instance of R1 and R2 Instance of R3

P3 Instance of R3 -------

11

22

P = { P1, P2, P3 }

R = { R1, R2, R3, R4 }

E = { P1R1, P2R3, R1P2, R2P2, R2P1 ,R3P3 }

The sets P, R, and E:

Page 76: Operating System Concepts

Q: Explain why: Although the graph contains a cycle, the system may Q: Explain why: Although the graph contains a cycle, the system may not in a deadlock state. not in a deadlock state.

Sol:Sol:

Case 1: The system has one instance per resource typeCase 1: The system has one instance per resource type

• If a cycle exists, the system in a deadlock state.If a cycle exists, the system in a deadlock state.

• Each process involved in the cycle is deadlocked. Each process involved in the cycle is deadlocked.

P1

R1R2

P2

CycleCycle

(Deadlock)(Deadlock)

As show, no chance to break the cycle As show, no chance to break the cycle because:because:

• No process can finish execution.No process can finish execution.

• No way to free a resource. No way to free a resource.

CycleCycle:

P1 P1 R1 R1 P2 P2 R2 R2

Page 77: Operating System Concepts

Case 2: The system has more than one instance per resource typeCase 2: The system has more than one instance per resource type

• If a cycle exists, the system may or may not be in a deadlock state.If a cycle exists, the system may or may not be in a deadlock state.

• Ex 1: a cycle with deadlock:Ex 1: a cycle with deadlock:

Two Cycles existsTwo Cycles exists:

P1 P1 R1 R1 P2 P2 R3 R3 P3 P3 R2R2

P2 P2 R3 R3 P3 P3 R2 R2

As show, P1, P2, and P3 are deadlockedAs show, P1, P2, and P3 are deadlocked

Page 78: Operating System Concepts

Ex 2: a cycle without deadlock:Ex 2: a cycle without deadlock:

CycleCycle:

P1 P1 R1 R1 P3 P3 R2 R2

There is no deadlock because:There is no deadlock because:

• P4 may release its instance of R2. P4 may release its instance of R2.

• This resource can be then allocated to This resource can be then allocated to P3 which breaking the cycle. P3 which breaking the cycle.

• Also P2 may release its instance of Also P2 may release its instance of R1.R1.

• This resource can be allocated to P1. This resource can be allocated to P1.

Page 79: Operating System Concepts

Q: Describe in details the basic rules used for deadlock avoidance . Q: Describe in details the basic rules used for deadlock avoidance .

Sol:Sol:

Examines the system state so that:Examines the system state so that:

System state

Safe Unsafe

No deadlockNo deadlock Possibility of deadlockPossibility of deadlock

• System in safe state if there exists a safe sequence of all System in safe state if there exists a safe sequence of all processesprocesses لتنفيذ امن ترتيب هناك كان اذا االمنة الحالة فى النظام لتنفيذ يكون امن ترتيب هناك كان اذا االمنة الحالة فى النظام يكون العملياتالعمليات

Avoidance Avoidance ensure that a system will never ensure that a system will never enter an unsafe state. enter an unsafe state.

Deadlock Avoidance

Page 80: Operating System Concepts

العمليات • لجميع يسمح الذى الترتيب هو للعمليات االمن العمليات الترتيب لجميع يسمح الذى الترتيب هو للعمليات االمن الترتيبامرار يتم بحيث الوقت بعض انتظرت لو حتى تنفيذها يتم امرار ان يتم بحيث الوقت بعض انتظرت لو حتى تنفيذها يتم ان

جميعها تنتهى حتى العمليات تلك بين جميعها المصادر تنتهى حتى العمليات تلك بين . .المصادر

<P<P11, P, P22, P, P33, P, P44, …….., P, …….., Pn-1n-1, P, Pnn>>

Can be executed by Can be executed by

resources it holds resources it holds + +

systems available resources.systems available resources.

Can be executed by Can be executed by

resources it holds resources it holds + + systems available resources. systems available resources. ++Resources held by PResources held by P11

1111

2222

1111

2222

3333

Can be executed by Can be executed by

resources it holds resources it holds + + systems available resources. systems available resources. ++Resources held by PResources held by P11, P, P22

1111

2222

3333

Page 81: Operating System Concepts

Avoidance Algorithms

Resource Allocation Graph Algorithm

Claim edge PClaim edge Pii ---> R ---> Rjj indicated that process P indicated that process Pjj may request resource Rmay request resource Rj j in future; in future; represented by a dashed line.represented by a dashed line.

Claim edge converts to request edge when a Claim edge converts to request edge when a process requests a resource.process requests a resource.

Request edge converted to an assignment Request edge converted to an assignment edge when the resource is allocated to the edge when the resource is allocated to the process.process.

Claim edge Claim edge Request edge Request edge Assignment edge Assignment edge

1111

2222

3333

Page 82: Operating System Concepts

Request EdgeRequest EdgeAssignment Assignment EdgeEdge

Claim EdgeClaim Edge

Suppose that process PSuppose that process Pi i requests a resource Rrequests a resource Rjj

The request can be granted only if converting the The request can be granted only if converting the request edge to an assignment edge does not result in request edge to an assignment edge does not result in a cycle in the resource allocation grapha cycle in the resource allocation graph

Page 83: Operating System Concepts

Case Study: consider the following resource Case Study: consider the following resource allocation graph:allocation graph:

Suppose that Suppose that PP22 requests R requests R22

Although RAlthough R22 is free, we can not allocate it to P is free, we can not allocate it to P22 since this creates a cycle since this creates a cycle

CycleCycle

Page 84: Operating System Concepts

Consider the following Resource allocation graphConsider the following Resource allocation graph

P1 P3

P2

R2

R3

R1

R4

• Is the system at safe state? What is the safe sequence? (if exists).

• Assume at T1, P3 requests R2, is it reasonable to grant this request?

Page 85: Operating System Concepts

P1 P3

P2

R2

R3

R1

R4

ProcessProcess Max. NeedMax. Need HoldHold

Steps:Steps:

1.1. Find the Available Resources.Find the Available Resources.

2.2. Construct the table: Construct the table:

3. Find the safe sequence.3. Find the safe sequence.

Page 86: Operating System Concepts

P1 P3

P2

R2

R3

R1

R4

ProcessProcess Max. NeedMax. Need HoldHold

P1P1 R1, R2, R3R1, R2, R3 R1, R3R1, R3

P2P2 R3, R4R3, R4 --------

P3P3 R1, R2, R3, R4R1, R2, R3, R4 R4R4

• Available Resources: R2Available Resources: R2

• Safe sequence: <P1, P3, P2> so system in safe state.

Page 87: Operating System Concepts

P1 P3

P2

R2

R3

R1

R4

At T1: (P3 requests R2)

• It is not reasonable to grant the request because system will be in unsafe state (because this may result in a future cycle if P1 requests R2).

cycle

Page 88: Operating System Concepts

Recovery From Deadlock

Terminate deadlocked processes

Free some Resources

Terminate all deadlockedTerminate all deadlocked processesprocesses

Terminate one by one Terminate one by one Until deadlock eliminatedUntil deadlock eliminated

• Free some resources Free some resources from the deadlocked processes.from the deadlocked processes.

• Give those resources to otherGive those resources to other processes until deadlock processes until deadlock eliminatedeliminated

Page 89: Operating System Concepts

Memory ManagementTechniques

الذاكرة ادارة أساليب

Page 90: Operating System Concepts

Q: explain what is meant by memory management, then Q: explain what is meant by memory management, then discuss why to manage memory?discuss why to manage memory?

Sol:Sol: Ready Queue

Process need Process need to be to be executedexecuted

Memory management is how to organize active processes (processes Memory management is how to organize active processes (processes currently in the ready queue) so that:currently in the ready queue) so that:

1.1. Processes can be easily reached.Processes can be easily reached.

2.2. Maximize memory space utilization. Maximize memory space utilization.

Page 91: Operating System Concepts

Q: show how a loader stores an executable file into the Q: show how a loader stores an executable file into the memory assuming:memory assuming:

• File of Size =20 memory words (instructions and data).File of Size =20 memory words (instructions and data).• Using Contiguous allocation method. Using Contiguous allocation method. • Repeat the problem three different times using:Repeat the problem three different times using:

• First fit.First fit.• Best fit.Best fit.• Worst Fit. Worst Fit.

Sol:Sol:

Executable file (Size =20 memory words)

MemoryMemory

LoaderLoader

??

Page 92: Operating System Concepts

1.1. تحميلة سيتم الذى للبرنامج مناسب مكان عن تحميلة البحث سيتم الذى للبرنامج مناسب مكان عن البحث (( المتجاور الـتسكين استخدام المتجاور بفرض الـتسكين استخدام يتم contiguous allocation contiguous allocation بفرض يتم حيث حيث

كـ البرنامج كـ تحميل البرنامج اجزاء block block تحميل على تجزئتة يتم وال متجاور اجزاء واحد على تجزئتة يتم وال متجاور واحد((منفصلةمنفصلة

الستيعاب الذكرة فى مناسبة فجوة عن البحث طريق عن ذلك يتم الستيعاب و الذكرة فى مناسبة فجوة عن البحث طريق عن ذلك يتم وهى و الطرق احد باستخدام هى البرنامج و الطرق احد باستخدام ::البرنامج

• فجوه : : First FitFirst Fit الـالـ اول فى البرنامج تسكين يتم فجوه حيث اول فى البرنامج تسكين يتم تستوعب تستوعب hole hole حيث) البرنامج ) على جدا كبيرة كانت لو حتى (البرنامج البرنامج ) على جدا كبيرة كانت لو حتى ..البرنامج

• مناسبة : : Best FitBest Fit الـالـ فجوة افضل فى البرنامج تسكين يتم مناسبة حيث فجوة افضل فى البرنامج تسكين يتم حيث) استخدام ) دون الفجوه فى كبيرة مساحة ترك يتم ال بحيث (للبرنامج استخدام ) دون الفجوه فى كبيرة مساحة ترك يتم ال بحيث ..للبرنامج

• للبرنامج : : Worst FitWorst Fit الـالـ مناسبة فجوه اكبر فى البرنامج تسكين للبرنامج يتم مناسبة فجوه اكبر فى البرنامج تسكين . .يتم

البرنامج مكان البرنامج تحديد مكان اختيارها تحديد تم التى الفجوة حسب الذاكرة اختيارها فى تم التى الفجوة حسب الذاكرة فى . الـ تحميل طريق عن ذلك يتم و البرنامج . الستيعاب الـ تحميل طريق عن ذلك يتم و البرنامج BaseBase RegisterRegister الستيعاب

اول اول بعنوان الـ wordword بعنوان تحميل و المختارة الفجوة الـ فى تحميل و المختارة الفجوة Limit registerLimit register فىالبرنامج يحتاجها التى البرنامج بالمساحة يحتاجها التى ..بالمساحة

تم التى الفجوة الى فعلى بشكل البرنامج تحميل هى الثالثة تم الوظيفة التى الفجوة الى فعلى بشكل البرنامج تحميل هى الثالثة الوظيفةالـ العناوين تحويل بعد الـ اختيارها العناوين تحويل بعد . .physicalphysical الىالى logicallogical اختيارها

الـ وظيفة ان هى loaderتزكر و مهام ثالثة فى تتلخص

Page 93: Operating System Concepts

Using First Fit

Executable file (Size =20 memory words)

LoaderLoader

MemoryMemory

OSOS

ProcessProcess

ProcessProcess

ProcessProcess

10001000

10101010

10401040

10701070

11001100

11251125

ProcessProcess

11501150

12001200

1250125012551255

ProcessProcess

1040

20

BaseBase

LimitLimit

Start Start address of address of processprocessLegal rangeLegal range

10601060

999999

00

Page 94: Operating System Concepts

Using Best Fit

Executable file (Size =20 memory words)

LoaderLoader

MemoryMemory

OSOS

ProcessProcess

ProcessProcess

ProcessProcess

10001000

10101010

10401040

10701070

11001100

11251125

ProcessProcess

11501150

12001200

1250125012551255

ProcessProcess

1100

20

BaseBase

LimitLimit

Start Start address of address of processprocessLegal rangeLegal range

11201120

Page 95: Operating System Concepts

Using Worst Fit

Executable file (Size =20 memory words)

LoaderLoader

MemoryMemory

OSOS

ProcessProcess

ProcessProcess

ProcessProcess

10001000

10101010

10401040

10701070

11001100

11251125

ProcessProcess

11501150

12001200

1250125012551255

ProcessProcess

1150

20

BaseBase

LimitLimit

Start Start address of address of processprocessLegal rangeLegal range

11701170

Page 96: Operating System Concepts

Q: Explain what is meant by “Bootstrapping”, then what is the Q: Explain what is meant by “Bootstrapping”, then what is the difference between “Loader” and “Bootstrap Loader”?difference between “Loader” and “Bootstrap Loader”?

Sol:Sol:

ما هو و لالستخدام جاهز يصبح حتى تشغيلة بداية عند الجهاز بها يقوم التى االجراءات ما هى هو و لالستخدام جاهز يصبح حتى تشغيلة بداية عند الجهاز بها يقوم التى االجراءات هىالتحميل مرحلة علية التحميل يطلق مرحلة علية . .يطلق

فقط للقراءة ذاكرة على مخزن ثابت برنامج خالل من االجراءات تلك بقراءة الجهاز فقط يقوم للقراءة ذاكرة على مخزن ثابت برنامج خالل من االجراءات تلك بقراءة الجهاز يقومROMROM (( بتحميلها المصنع بتحميلها يقوم المصنع . . BootstrapBootstrap ProgramProgram يسمىيسمى ( (يقوم

الـ الـ يقوم و BootstrapBootstrap ProgramProgram يقوم صحيح بشكل اتصالها من التاكد و الجهاز اجزاء و باختبار صحيح بشكل اتصالها من التاكد و الجهاز اجزاء باختبار . ما باستدعاء يقوم الجهاز اجزاء جميع سالمة من يتاكد عندما و خطا اى تصحيح . محاولة ما باستدعاء يقوم الجهاز اجزاء جميع سالمة من يتاكد عندما و خطا اى تصحيح محاولة

الـ الـ يسمى النظام BootstrapBootstrap loaderloader يسمى ليبدا الذاكرة الى التشغيل نظام بتحميل يقوم النظام الذى ليبدا الذاكرة الى التشغيل نظام بتحميل يقوم الذىالعمل العمل فى . .فى

Actions taken when a computer is first powered on until it is ready to be Actions taken when a computer is first powered on until it is ready to be used .used .

Computer reads a program from a ROM (Computer reads a program from a ROM (Read Only MemoryRead Only Memory) which:) which:

Is installed by the manufacturer.Is installed by the manufacturer.

Contains bootstrap program and some other routines that controls Contains bootstrap program and some other routines that controls hardware (hardware (BIOSBIOS))

BootstrappingROM

Bootstrap programBootstrap program

Bootstrap LoaderBootstrap Loader

Page 97: Operating System Concepts

• An absolute loader.An absolute loader.• Executed when a computer is turned on or restarted.Executed when a computer is turned on or restarted.• Loads the first program to be run by the computer (usually an OS).Loads the first program to be run by the computer (usually an OS).• loads at address 0 in the memory (so that it is an absolute loader). loads at address 0 in the memory (so that it is an absolute loader).

Bootstrap Loader

الـ يسمى خاص برنامج على يحتوى التشغيل نظام ان الـ الحظ يسمى خاص برنامج على يحتوى التشغيل نظام ان عى LoaderLoaderالحظ لتحميل استدعاؤة يتم الذى عى و لتحميل استدعاؤة يتم الذى و . الـ ان اى الذاكرة الى جديدة . عملية الـ ان اى الذاكرة الى جديدة . loaderloaderعملية التشغيل نظام من جزء . هو التشغيل نظام من جزء هو

: نفسة؟ التشغيل نظام تحميل عن المسئول من هو االن : السؤال نفسة؟ التشغيل نظام تحميل عن المسئول من هو االن السؤال

الـ انواع من بسيط نوع يوجد انة ببساطة الـ االجابة انواع من بسيط نوع يوجد انة ببساطة الـ LoadersLoadersاالجابة الـ يسمى هو Bootstrap loaderBootstrap loaderيسمى يكون الذى هو و يكون الذى والـ على الـ ايضا على الـ ROMROMايضا تخزن الـ التى تخزن الـ. Bootstrap programBootstrap programالتى الـ. هذا نظام LoaderLoaderهذا تحميل عن المسئول نظام هو تحميل عن المسئول هو

العنوان فى العنوان التشغيل فى . 00التشغيل الـ هذا لبساطة نظرا و الذاكرة . من الـ هذا لبساطة نظرا و الذاكرة يسمى loaderloaderمن يسمى فانة . . Absolute LoaderAbsolute Loaderفانة

Loader

• A part or OS.A part or OS.• Perform Perform loadingloading and and relocationrelocation for user’s programs. for user’s programs.

Page 98: Operating System Concepts

Q: Explain why? The bootstrap loader is an absolute (Q: Explain why? The bootstrap loader is an absolute (SimpleSimple) loader? ) loader?

Sol: Sol:

OS00

999999

OS00

999999

MemoryMemory

DiskDisk

Bootstrap Bootstrap LoaderLoader

• Assuming OS requires 1000 words (from 0 to 999).Assuming OS requires 1000 words (from 0 to 999).• As shown, the range of the logical address (As shown, the range of the logical address (in the executable copy of OSin the executable copy of OS) in the ) in the disk is the same of the physical address range in memory.disk is the same of the physical address range in memory.•So, no relocation.So, no relocation.

Range of logical Range of logical addressesaddresses

Range of physical Range of physical addressesaddresses

No Relocation

Page 99: Operating System Concepts

Q: Explain in details how to manage memory in multi-programming Q: Explain in details how to manage memory in multi-programming environment?environment?

Sol: Sol:

Memory Management In multi-programming environment

Swapping

Contagious allocation

Paging

Page 100: Operating System Concepts

• A process can be swapped out of memory to disk, and then brought back into A process can be swapped out of memory to disk, and then brought back into memory for continued execution.memory for continued execution.

Swapping:

Q: Explain what is meant by “Q: Explain what is meant by “swapping”swapping”, Give some examples for swapping. , Give some examples for swapping.

Sol:Sol:

Page 101: Operating System Concepts

Multi-programming environment with “Multi-programming environment with “priority schedulingpriority scheduling” ”

• Assume a system with 32 kb memory size.Assume a system with 32 kb memory size.• 5kb are used for OS, 10 kb for the low priority process. 5kb are used for OS, 10 kb for the low priority process. • Hence, the available space is 17 kb. Hence, the available space is 17 kb. • A higher priority process arrives and needs 20 kb. A higher priority process arrives and needs 20 kb.

OS (5 kb)OS (5 kb)

Low Priority Low Priority process (10 process (10 kb)kb)

Available Available 17 Kb17 Kb

OS (5 kb)OS (5 kb)

Available Available 27 Kb27 Kb

OS (5 kb)OS (5 kb)

High Priority High Priority process (20 process (20 kb)kb)

Available Available 7 Kb7 Kb

OS (5 kb)OS (5 kb)

Available Available 27 Kb27 Kb

SwapSwap in the highin the high

priority processpriority processhigh priority process high priority process finishes executionfinishes execution

Swap out the Swap out the low priority low priority process to diskprocess to disk

DiskDisk

Swap in the low priority process again to Swap in the low priority process again to resume executionresume execution

High High PriorityPriority 20 Kb20 Kb

Ex1:

Page 102: Operating System Concepts

Q: Explain what is meant by contiguous allocation, what are its different Q: Explain what is meant by contiguous allocation, what are its different types? types?

Sol:Sol:

Contiguous Allocation

• In contiguous allocation, each process is contained in a single In contiguous allocation, each process is contained in a single contiguous section of memory.contiguous section of memory.

ال • و الذاكرة من واحد جزء فى العملية تسكين يتم المتجاور التسكين حالة ال فى و الذاكرة من واحد جزء فى العملية تسكين يتم المتجاور التسكين حالة فى . جزء من اكثر الى العملية تقسيم . يتم جزء من اكثر الى العملية تقسيم يتم

Page 103: Operating System Concepts

Methods for Contiguous Allocation

Simple Method

General Method

Page 104: Operating System Concepts

Simple Method

• Divide memory into several fixed-sized partitions.Divide memory into several fixed-sized partitions.

• Each partition contains one process. Each partition contains one process.

• Degree of multiprogramming is bound by the number of partitions.Degree of multiprogramming is bound by the number of partitions.

• When a partition is free, a process is selected from the input queue and is When a partition is free, a process is selected from the input queue and is loaded into the free partition. loaded into the free partition.

• When the process terminates, the partition becomes available for another When the process terminates, the partition becomes available for another process.process.

• its no longer used its no longer used (Explain why?)(Explain why?) because it has various drawbacks like: because it has various drawbacks like:1.1. Degree of multiprogramming is bounded by the number of Degree of multiprogramming is bounded by the number of

partions.partions.2.2. Internal fragmentations. Internal fragmentations.

X

Page 105: Operating System Concepts

7 KB9 KB8 KB4 KB

Assuming a memory of 30 KB divided into three partitions as following: Assuming a memory of 30 KB divided into three partitions as following:

Input QueueInput Queue (in the disk)(in the disk)

10 10 KBKB

10 10 KBKB

10 10 KBKB

This method suffers from This method suffers from internal fragmentationsinternal fragmentations..•The degree of The degree of multiprogrammingmultiprogramming is bounded to 3 although it can be is bounded to 3 although it can be 4. 4.

Process 1(7 KB)

Process 2(9 KB)

Process 3(8 KB)

Internal Internal FragmentationFragmentation

As shown

Page 106: Operating System Concepts

General Method

• Initially, all memory is available for user processes, and is considered as Initially, all memory is available for user processes, and is considered as one large block of available memory.one large block of available memory.

• When a process arrives and needs memory, we search for a hole large When a process arrives and needs memory, we search for a hole large enough for this process using. enough for this process using.

• If we find one, we allocate only as much memory as is needed, keeping If we find one, we allocate only as much memory as is needed, keeping the rest available to satisfy future requests.the rest available to satisfy future requests.

First Fit Best Fit Worst Fit

Page 107: Operating System Concepts

•There are three different methods to find the suitable hole for There are three different methods to find the suitable hole for a process?:a process?:

• First fit:First fit: allocate the first hole that is big enough (fastest allocate the first hole that is big enough (fastest method). method).

• Best fit:Best fit: allocate the smallest hole that is big enough allocate the smallest hole that is big enough (produces the smallest leftover hole).(produces the smallest leftover hole).

• Worst fit:Worst fit: allocate the largest hole (produces the largest allocate the largest hole (produces the largest leftover hole which may be more useful than the smaller leftover hole which may be more useful than the smaller leftover hole from a best-fit approach. leftover hole from a best-fit approach.

X

Page 108: Operating System Concepts

4 KB 7 KB9 KB8 KB

Input QueueInput Queue (in the disk)(in the disk)

As shown:As shown:•The degree of multiprogramming changing according to the number The degree of multiprogramming changing according to the number of processes in the memory (of processes in the memory (in ready queuein ready queue). ).

Process 1(7 KB)

Process 2(9 KB)

Process 3(8 KB)

OSOS

Process 4(4 KB)

Process 5(9 KB)

Page 109: Operating System Concepts

4 KB 7 KB9 KB8 KB

Input QueueInput Queue (in the disk)(in the disk)

As shown:As shown:• This method suffers from external Fragmentations. This method suffers from external Fragmentations.

Process 2

Process 3

OSOS

Process 4

Process 9

Process 20

External External FragmentationsFragmentations

After a period of time External Fragmentations appear

Page 110: Operating System Concepts

4 KB 7 KB9 KB8 KB

Input QueueInput Queue (in the disk)(in the disk)

Compaction:Compaction:• Is a movement of the memory contents to place all free memory in a one large block Is a movement of the memory contents to place all free memory in a one large block sufficient to store new process. sufficient to store new process. • It is a solution for the external fragmentation but it is expensive and is not always It is a solution for the external fragmentation but it is expensive and is not always possible. possible.

Process 2

Process 3

OSOSProcess 4

Process 9

Process 20

Compaction

Process 2

Process 3

OSOS

Process 4

Process 9

Process 20

A new hole to store a A new hole to store a new processnew process

Page 111: Operating System Concepts

Paging

• Paging is a memory-management scheme that permits the physical-Paging is a memory-management scheme that permits the physical-address space of a process to be noncontiguous.address space of a process to be noncontiguous.

• it is commonly used in most operating systems.it is commonly used in most operating systems.

• Divide physical memory into fixed-sized blocks called frames.Divide physical memory into fixed-sized blocks called frames.

• Divide Process into blocks of same size called pages.Divide Process into blocks of same size called pages.

• Use a page table which contains base address of each page in physical Use a page table which contains base address of each page in physical memory.memory.

X

Page 112: Operating System Concepts

Example

Process Process PP

Page Page numbernumber

Frame Frame numbernumber00

11

22

33

Page Page numbernumber

A process P is divided into 4 pages.

• The process will be loaded into 4 frames.The process will be loaded into 4 frames.• The page number is used as index to the page table. The page number is used as index to the page table. • The page table contains the frame number for each page. The page table contains the frame number for each page.

Page 113: Operating System Concepts

Paging Example32-byte memory, each memory word of size =1 byte (can store only one 32-byte memory, each memory word of size =1 byte (can store only one character), the size of page (and frame also)= 4-byte. character), the size of page (and frame also)= 4-byte.

• Show how to store 4 pages process into memory using a page table. Show how to store 4 pages process into memory using a page table. • according to your page table, what are the physical addresses according to your page table, what are the physical addresses corresponding to the logical addresses 4 and 13. corresponding to the logical addresses 4 and 13.

Sol:Sol:• Memory size=32 Byte =32 words.Memory size=32 Byte =32 words.• Page size = Frame size = 4 bytes =4 words.Page size = Frame size = 4 bytes =4 words.• Number of Frames = 32/4 = 8 Frames Number of Frames = 32/4 = 8 Frames (addressed from 0 (addressed from 0 7) 7)

Page 114: Operating System Concepts

Frame Frame 00

Frame Frame 11

Frame Frame 22

Frame Frame 33

Frame Frame 44

Frame Frame 55

Frame Frame 66

Frame Frame 77

Logical addressLogical address Page 0 ContentsPage 0 Contents

Page 0Page 0

PagePage 11

PagePage 22

PagePage 33

4 Page 4 Page processprocess

Physical addressPhysical address

Page 115: Operating System Concepts

1.1. No external fragmentation.No external fragmentation.2.2. Allow the process components to be noncontiguous. Allow the process components to be noncontiguous.

1.1. A possibility of internal fragmentations that can not be used. A possibility of internal fragmentations that can not be used.

Q: Explain when you have internal fragmentations when using the paging Q: Explain when you have internal fragmentations when using the paging technique.technique.

Sol: Sol: when the contents of the last page of the process is less than the frame when the contents of the last page of the process is less than the frame

size, then the remaining part of the frame will be an internal size, then the remaining part of the frame will be an internal fragmentations that can not be used. fragmentations that can not be used.

Advantages of paging:

Problems in paging:

Page 116: Operating System Concepts

Any Questions?