35
CPU Scheduling AIM: Write a program to display all t he CPU Scheduling algorithms. THEORY: An operating system must allocate computer resources among the potentially competing requirements of multiple processes. In the case of the processor, the resource to be allocated is execution time on the processor and the means of allocation is scheduling. Various CPU scheduling algorithms include: First Come First Served (FCFS): As each process becomes ready, it joins the ready queue.When the currently running process ceases to execute, the process that has been in the ready queue the longest is selected for running. FCFS performs much better for long processes than short ones. Shortest Process Next (SPN): This is a non- preemptive policy in which the process with the shortest expected processing time is selected next. Shortest Remaining Time(SRT): The shortest remaining time (SRT) policy is a preemptive version of SPN. In this case, the scheduler always chooses the process that has the shortest expected remaining processing time. Round Robin(RR): A clock interrupt is generated at periodic intervals.When the interrupt occurs, the currently running process is placed in the ready queue, and the next ready job is selected on a FCFS basis.This technique is also known as time slicing Highest Response Ratio Next (HRRN): For each individual process, we would like to minimize the ratio of turnaround time to actual service time, and also to minimize the average value over all processes. This is the basis of HRRN.  Feedback: The operating system allocates the processor to a process and, when the process blocks or is preempted (by clock), feeds it back into one of several priority queues. LOGIC: START. Accept number of processes, the arrival and service t imes for each process from the user. Sort the processes based on their arrival times into a process Array. Accept the scheduling algorithm to be executed from the user. For FCFS: Increment Time_Counter to value equivalen t to sum of arrival time and service time of 1 st process which is now the finish time for that process. Select next process from the sorted array having arrival time less than Time_Counter and do the following: T f = T s + Time_Counter; Time_Counter = Time_Counter + T s ; Display the Time_Counter, Process currently in CPU and Process that has completed execution for that time period in tabular form. For SPN: Here, all those processes whose arrival times are before than Time_Counter value are again sorted internally based on their Service times. Follow same steps as that of FCFS from Step 5(ii). For HRRN: Here, all those processes whose arrival times are before than Time_Counter value are again sorted internally based on Highest Response Ratios where Response Ratio is calculated as: HRR = 1 + Wait Time . Serve Time Follow same steps as that of FCFS from Step 5(ii).

OS Practs Fin

Embed Size (px)

Citation preview

Page 1: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 1/35

CPU SchedulingAIM: Write a program to display all the CPU Scheduling algorithms.

THEORY:

An operating system must allocate computer resources among the potentially

competing requirements of multiple processes. In the case of the processor, the resource to be

allocated is execution time on the processor and the means of allocation is scheduling.

Various CPU scheduling algorithms include:

First Come First Served (FCFS): As each process becomes ready, it joins the ready

queue.When the currently running process ceases to execute, the process that has been in the

ready queue the longest is selected for running. FCFS performs much better for long

processes than short ones.

Shortest Process Next (SPN): This is a non- preemptive policy in which the process with the

shortest expected processing time is selected next.

Shortest Remaining Time(SRT): The shortest remaining time (SRT) policy is a preemptive

version of SPN. In this case, the scheduler always chooses the process that has the shortestexpected remaining processing time.

Round Robin(RR): A clock interrupt is generated at periodic intervals.When the interrupt

occurs, the currently running process is placed in the ready queue, and the next ready job is

selected on a FCFS basis.This technique is also known as time slicing

Highest Response Ratio Next (HRRN): For each individual process, we would like to

minimize the ratio of turnaround time to actual service time, and also to minimize the average

value over all processes. This is the basis of HRRN. 

Feedback: The operating system allocates the processor to a process and, when the process

blocks or is preempted (by clock), feeds it back into one of several priority queues.

LOGIC:START.

Accept number of processes, the arrival and service times for each process from the user.

Sort the processes based on their arrival times into a process Array.

Accept the scheduling algorithm to be executed from the user.

For FCFS:

Increment Time_Counter to value equivalent to sum of arrival time and service time of 1st 

process which is now the finish time for that process.

Select next process from the sorted array having arrival time less than Time_Counter and do

the following:

Tf  = Ts + Time_Counter;

Time_Counter = Time_Counter + Ts;Display the Time_Counter, Process currently in CPU and Process that has completed

execution for that time period in tabular form.

For SPN:

Here, all those processes whose arrival times are before than Time_Counter value are again

sorted internally based on their Service times.

Follow same steps as that of FCFS from Step 5(ii).

For HRRN:

Here, all those processes whose arrival times are before than Time_Counter value are again

sorted internally based on Highest Response Ratios where Response Ratio is calculated as:

HRR = 1 + Wait Time .

Serve Time

Follow same steps as that of FCFS from Step 5(ii).

Page 2: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 2/35

For SRT:

The Remaining Time for each process is calculated as:

rem_time = Ts  – Time spent in execution

Start Time_Counter from Arrival time of 1st

process in sorted array.

For cur_proc denoting Current process that is executing, check if any other process has

arrival time <= Time_Counter. For all such processes that satisfy above condition, select theprocess having least rem_time, pre-empting the currently running process. New_proc

becomes the cur_proc.

If above condition is not satisfied, continue executing cur_proc.

When rem_time for a process becomes 0, it is considered finished.

Display the Time_Counter, Process currently in CPU and Process that has completed

execution for that time period in tabular form.

Increment Time_Counter by 1 and go to step (iii) until no more processes are left for

executing.

For RR:

Accept quant (time-quantum) value from the user.

Set rem_time for all process equivalent to their respective service-times.Start Time_Counter from Arrival time of 1

stprocess in sorted array.

If(cur_proc.rem_time > quant) then

cur_proc.rem_time = cur_proc.rem_time – quant;

Time_Counter = Time_Counter + quant;

Send cur_proc to the back of the queue and continue execution with the process at the front

of the queue.

Else

Cur_proc.finish_time = Time_Counter + cur_proc.rem_time;

Time_Counter = Time_Counter + (quant-cur_proc.rem_time);

Select process at the front of the queue having arrival time less than

Time_Counter value.

Display the Time_Counter, Process currently in CPU and Process that has completed

execution for that time period in tabular form.

For Feedback:

Accept quant (time-quantum) value from the user.

Set rem_time for all process equivalent to their respective service-times.

Start Time_Counter from Arrival time of 1st

process in sorted array.

If(cur_proc.rem_time > quant) then

cur_proc.rem_time = cur_proc.rem_time – quant;

Time_Counter = Time_Counter + quant;Send cur_proc to the back of the next lower-priority queue (if available) and continue

execution with the process at the front of the higher-priority queue. If there are no processes

present in high-priority queue then start executing processes from lower priority queues.

Else

Cur_proc.finish_time = Time_Counter + cur_proc.rem_time;

Time_Counter = Time_Counter + (quant-cur_proc.rem_time);

Select process at the front of the queue having arrival time less than

Time_Counter value.

Display the Time_Counter, Process currently in CPU and Process that has completed

execution for that time period in tabular form.

Page 3: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 3/35

Display table for that scheduling algorithm containing process name, arrival time, service

time, finish time, turnaround time and average turn around and average of the ratio of 

turnaround time to service time.

If user wishes to continue, goto step 4 else goto step 8.

STOP.

PROGRAM:#include<stdio.h>#include<iostream.h>#include<conio.h>#include<string.h>#include<ctype.h>

int nop; //nop-> Number of Processvoid getProcess();void STFNP(int);

void STFP();void showTable();void FeedBack();

void RR();struct Process{ char p_nm[5]; //p_nm-> Process Name

intarrival_time,service_time,finish_time,rem_time,tr;

float tr_by_ts;} p[10],temp_p;

void main(){

clrscr();int sp;char choice='y';getProcess();

while(choice=='y'){

printf("\n\n1.FCFS\n2.SRTF-NP\n3.STFP\n4.RoundRobin\n5.FeedBack");

printf("\n Select the Process Sheduling : ");scanf("%d",&sp);switch(sp){

case 1: STFNP(1); break;case 2: STFNP(2); break;case 3: STFP(); break;case 4: RR(); break;case 5: FeedBack(); break;default : printf("\nInvalid Selection ");

}

showTable();printf("\n\nWould you like to continue?");

Page 4: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 4/35

flushall();scanf("%c",&choice);

}

getch();

}void getProcess(){

int i,j;char

d_p[10][5]={"P1","P2","P3","P4","P5","P6","P7","P8","P9","P10"};

printf("Enter the number of process : ");scanf("%d",&nop);for(i=0;i<nop;i++){ strcpy(p[i].p_nm,d_p[i]);

printf("Enter Arrival time and Service time ofprocess P%d :",i+1);

scanf("%d%d",&p[i].arrival_time,&p[i].service_time);p[i].rem_time=p[i].service_time;

}for(i=0;i<nop;i++)

for(j=i+1;j<nop;j++)if(p[i].arrival_time>p[j].arrival_time){

temp_p=p[i];p[i]=p[j];

p[j]=temp_p;}

printf("\nProcess\tArrival_Time\tService_Time\n\n");for(i=0;i<nop;i++)printf("

%s\t\t%d\t\t%d\n",p[i].p_nm,p[i].arrival_time,p[i].service_time);}void showTable(){

int i;

float castf;printf("\nProcess\tArrival_Time\tService_Time\tFinish_tim

e\tTr\tTr/Ts\n");for(i=0;i<nop;i++){

p[i].tr=p[i].finish_time-p[i].arrival_time;castf=p[i].tr;p[i].tr_by_ts=castf/p[i].service_time;printf("\n

%s\t\t%d\t\t%d\t%d\t\t%d\t%f\n",p[i].p_nm,p[i].arrival_time,p[i].service_time,p[i].finish_time,p[i].tr,p[i].tr_by_ts);

}}

Page 5: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 5/35

void STFNP(int sheduling){

int i,j,curr_time=p[0].arrival_time,temp;printf("\n\tFCFS :\n\n");printf("

Time\tReady_Queue\tProcessor\tProcess_Completion\n");printf("\n %d\t%s\t\t%s",curr_time,p[0].p_nm,p[0].p_nm);curr_time=curr_time+p[0].service_time;for(i=1;i<=nop;i++){

printf("\n %d\t",curr_time);for(j=i;j<nop;j++)

if(p[j].arrival_time<=curr_time)printf("%s,",p[j].p_nm); //puts in ready queue

if(i<nop)printf("\b");

if(sheduling==2){

temp_p=p[i];for(j=i;j<nop;j++)

if(p[j].arrival_time<=curr_time){

if(temp_p.service_time>p[j].service_time){

temp_p=p[j];temp=j;

}}

p[temp]=p[i];p[i]=temp_p;

}printf("\t\t%s\t\t%s\n",p[i].p_nm,p[i-1].p_nm);p[i-1].finish_time=curr_time;curr_time=curr_time+p[i].service_time;

}}void RR()

{int temp=0,old_temp=0,i,j,q,t=p[0].arrival_time;printf("Enter the time Quantum : ");scanf("%d",&q);printf("

Time\tReady_Queue\t\tProcessor\tProcess_Completion\n");for(i=0;i<nop;i++)

t=t+p[i].service_time;for(i=p[0].arrival_time;i<t;i=i+q){

printf("\n %d\t",i);

for(j=temp;j<temp+nop;j++){

Page 6: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 6/35

if(j<nop){

if(p[j].arrival_time<=i &&p[j].rem_time>0)

printf("%s,",p[j].p_nm);

}else

if(p[j-nop].arrival_time<=i && p[j-nop].rem_time>0)

printf("%s,",p[j-nop].p_nm);}printf("\b");while(1){

if(temp>=nop)temp=0;

if(p[temp].arrival_time<=i &&p[temp].rem_time>=q)

{printf("\t\t\t%s",p[temp].p_nm);p[temp].rem_time-=q;break;

}else if(p[temp].arrival_time<=i &&

p[temp].rem_time>0){

printf("\t\t\t%s",p[temp].p_nm);

i=i-(q-p[temp].rem_time);p[temp].rem_time=0;break;

}temp++;

}if(p[old_temp].rem_time==0){

printf("\t\t%s",p[old_temp].p_nm);p[old_temp].finish_time=i;

}

old_temp=temp;temp++;

}p[old_temp].finish_time=i;printf("\n %d\t\t\t\t\t\t%s",i,p[old_temp].p_nm);

}void STFP(){

int old_temp=0,new_temp=0,i,k,j,t=p[0].arrival_time;temp_p=p[0];printf("

Time\tReady_Queue\t\tProcessor\tProcess_Completion\n");printf("\n %d\t%s\t\t\t%s",t,p[0].p_nm,p[0].p_nm);

Page 7: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 7/35

for(i=0;i<nop;i++)t=t+p[i].service_time;

for(i=p[0].arrival_time;i<t;i++){

for(j=0;j<nop;j++)

{if(p[j].arrival_time<=i){

if(p[j].rem_time>0 &&(p[j].rem_time<p[old_temp].rem_time ||p[old_temp].rem_time==0))

new_temp=j;}

}if(old_temp!=new_temp){

printf("\n %d\t",i);for(j=0;j<nop;j++)

if(p[j].arrival_time<=i &&p[j].rem_time>0)

printf("%s,",p[j].p_nm);printf("\b");printf("\t\t\t%s",p[new_temp].p_nm);if(p[old_temp].rem_time==0){

printf("\t\t%s",p[old_temp].p_nm);p[old_temp].finish_time=i;

}old_temp=new_temp;temp_p=p[new_temp];

}if(p[old_temp].rem_time>0)p[old_temp].rem_time--;

}p[old_temp].finish_time=i;printf("\n %d\t\t\t\t\t\t%s",i,p[old_temp].p_nm);

}

void FeedBack(){

int temp=0,old_temp=0,i,j,q,t=p[0].arrival_time,flag=0;printf("Enter the time Quantum : ");scanf("%d",&q);printf("

Time\tReady_Queue\t\tProcessor\tProcess_Completion\n");printf(" \tQ1 Q2 Q3\n");

for(i=0;i<nop;i++)

t=t+p[i].service_time;for(i=p[0].arrival_time;i<t;i=i+q)

Page 8: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 8/35

{printf("\n %d\t",i);for(j=temp;j<temp+nop;j++){

if(j<nop)

{if(p[j].arrival_time<=i &&

p[j].rem_time==p[j].service_time && p[j].rem_time>0){

printf("%s,",p[j].p_nm);flag++;

}}else

if(p[j-nop].arrival_time<=i && p[j-nop].rem_time==p[j-nop].service_time && p[j-nop].rem_time>0)

{printf("%s,",p[j-nop].p_nm);flag++;

}}if(flag==0)printf(" ");else{

printf("\b ");flag=0;

}

for(j=temp;j<temp+nop;j++){

if(j<nop){

if(p[j].arrival_time<=i &&p[j].rem_time==p[j].service_time-q && p[j].rem_time>0)

{printf("%s,",p[j].p_nm);

flag++;}

}else

if(p[j-nop].arrival_time<=i && p[j-nop].rem_time==p[j-nop].service_time-q && p[j-nop].rem_time>0)

{printf("%s,",p[j-nop].p_nm);flag++;

}

}if(flag==0)

Page 9: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 9/35

printf(" ");else{

printf("\b ");flag=0;

}

for(j=temp;j<temp+nop;j++){

if(j<nop){

if(p[j].arrival_time<=i &&p[j].rem_time<p[j].service_time-q && p[j].rem_time>0)

{printf("%s,",p[j].p_nm);flag++;

}}else

if(p[j-nop].arrival_time<=i && p[j-nop].rem_time<p[j-nop].service_time-q && p[j-nop].rem_time>0)

{printf("%s,",p[j-nop].p_nm);flag++;

}

}

if(flag==0)printf(" ");elseprintf("\b ");flag=0;

while(1){

if(temp>=nop)temp=0;

if(p[temp].arrival_time<=i &&p[temp].rem_time>=q)

{printf("\t\t\t%s",p[temp].p_nm);p[temp].rem_time-=q;break;

}else if(p[temp].arrival_time<=i &&

p[temp].rem_time>0){

printf("\t\t\t%s",p[temp].p_nm);

i=i-(q-p[temp].rem_time);p[temp].rem_time=0;

Page 10: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 10/35

break;}temp++;

}if(p[old_temp].rem_time==0){

printf("\t\t%s",p[old_temp].p_nm);p[old_temp].finish_time=i;

}old_temp=temp;temp++;

}p[old_temp].finish_time=i;

printf("\n %d\t\t\t\t\t\t%s",i,p[old_temp].p_nm);}OUTPUT:

Page 11: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 11/35

 

Page 12: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 12/35

Banker’s Algorithm AIM: Write a program to implement Banker’s Algorithm.

THEORY:

The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed

by E. Dijkstra that tests for safety by simulating the allocation of predetermined maximum

possible amounts of all resources, and then makes a “safe-state” check to test for possible

deadlock conditions for all other pending activities, before deciding whether allocation

should be allowed to continue. Several data structures must be maintained to implement the

banker's algorithm. Let n be the number of processes in the system and m be the number of 

resource types. We need the following data structures:

• Available. A vector of length m indicates the number of available resources of each type. If 

Available[j] equals k, there are k instances of resource type R j available.

• Max. An n x m matrix defines the maximum demand of each process. If Max[i][j] equals k,

then process Pi may request at most k instances of resource type R j.

• Allocation. An n x in matrix defines the number of resources of each type currentlyallocated to each process. If Allocation[i][j] equals k, then process Pi is currently allocated k 

instances of resource type R j.

• Need. An n x m matrix indicates the remaining resource need of each process. If Need[i][j]

equals k, then process Pi may need k more instances of resource type R j to complete its task.

Note that Need[i][j] equals Max[i][j] - Allocation[i][j].

LOGIC:

Safety Algorithm:

1. Let Work and Finish be vectors of length in and n, respectively. Initialize Work =

Available and Finish[i] - false for i = 0 , 1 , ..., n - l .

2. Find i such that botha. Finish[i] = = false

b. Needi <= Work 

If no such i exists, go to step 4.

3. Work = Work + Allocation,

Finish[i] = true

Go to step 2.

4. If Finish[i] = = true for all i, then the system is in a safe state.

 Resource – Request Algorithm:

We now describe the algorithm which determines if requests for a particular process Pi can be

safely granted. Let Request be the request vector for process P. If Request[j] = = k, thenprocess P, wants k instances of resource type R j. When a request for resources is made by

process Pi, the following actions are taken:

If Requesti, < Needi, go to step 2. Otherwise, raise an error condition, since the process has

exceeded its maximum claim.

2. If Requesti < Available, go to step 3. Otherwise, Ps must wait, since the resources are not

available.

3. Have the system pretend to have allocated the requested resources to process Pi by

modifying the state as follows:

Available = Available – Requesti;

Allocation = Allocation + Requesti;

Needi = Necdi  – Requesti;

Page 13: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 13/35

If the resulting resource-allocation state is safe, the transaction is completed, and process Pi is

allocated its resources.

PROGRAM:#include<stdio.h>

#include<conio.h>#include<stdlib.h>

void main(){

intalloc[10][10],need[10][10],avail[10],max[10][10],finish[10],pc=0;

int i,j,nop,nor,flag;clrscr();

printf("\nEnter the number of processes:");scanf("%d",&nop);

printf("\nEnter the number of resources:");scanf("%d",&nor);printf("\nEnter Alloc. Matrix:\n");for(i=0;i<nop;i++){

printf("P%d\t",i);for(j=0;j<nor;j++){

scanf("%d",&alloc[i][j]);}finish[i]=0;

}printf("\nEnter Max Matrix:\n");for(i=0;i<nop;i++){

printf("P%d\t",i);for(j=0;j<nor;j++){

scanf("%d",&max[i][j]);

need[i][j]=max[i][j]-alloc[i][j];if(need[i][j]<0){

printf("\nAllocation cannot be greaterthan max");

getch();exit(1);

}}

}printf("\nEnter available matrix:\n");

for(i=0;i<nor;i++)scanf("%d",&avail[i]);

Page 14: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 14/35

 while(pc<nop){

flag=0;for(i=0;i<nop;i++)

{if(finish[i]==0){

for(j=0;j<nor;j++){

if(need[i][j]>avail[j])break;

}if(j==nor){

flag=1;

for(j=0;j<nor;j++)avail[j]+=alloc[i][j];

finish[i]=1;pc++;printf("P%d ",i);break;

}}

}if(flag==0)

{printf("\nDeadlock occured!");getch();exit(1);

}}getch();

Page 15: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 15/35

OUTPUT:

Page 16: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 16/35

Page ReplacementAIM: Write a program to implement Page Replacement Algorithms.

THEORY:

There are certain basic algorithms that are used for the selection of a page to replace.

First-In-First-Out (FIFO): This policy treats the page frames allocated to a process as a

circular buffer, and pages are removed in round-robin style. All that is required is a pointer

that circles through the page frames of the process. This is therefore one of the simplest page

replacement policies to implement.

Optimal Policy: This selects for replacement that page for which the time to the next

reference is the longest. This policy is impossible to implement, because it would require the

operating system to have perfect knowledge of future events.

Least Recently Used (LRU): This policy replaces the page in memory that has not been

referenced for the longest time. By the principle of locality, this should be the page least

likely to be referenced in the near future.

Clock Policy: This policy requires the association of an additional bit with each frame,referred to as the use bit. When a page is first loaded into a frame in memory, the use bit for

that frame is set to 1.Whenever the page is subsequently referenced (after the reference that

generated the page fault), its use bit is set to 1. When it comes time to replace a page, the

operating system scans the buffer to find a frame with a use bit set to zero. Each time it

encounters a frame with a use bit of 1, it resets that bit to zero and continues on. If any of the

frames in the buffer have a use bit of zero at the beginning of this process, the first such

frame encountered is chosen for replacement.

LOGIC:

START.

Accept number of Page Requests (totalpages), number of Frames (totalframes) and the actualPage Requests (input[ ]) from the user.

Reset table entries to -1(empty), table[0][0] = input [0], i=0, flag=0, ppage=1, pframe=1

where table[][] is a 2D array representing the Page Table, i is a counter, flag denotes if the

requested page is already present in the table or not, pframe increments cyclically from 0 to

totalframes.

For FIFO:

Initialise flag = 0;

for(i=0 ; i<totalframes; i++)

{

if (table[ppage-1][i] is not empty && table[ppage-1][i] = = input[i])

{ table[ppage][i]=table[ppage-1][i];set flag = 1; //Requested page is already in table so no page fault

}

}

If the flag is 0, then copy input[ppage] to table[ppage][pframe] and increment pframe by 1

cyclically.

For all other non-empty (not -1) table[][] entries, copy contents of table[ppage-1][] to

table[ppage][].

Increment ppage by 1.

Repeat all above steps for FIFO until ppage = = totalpages.

Calculate PFaults() in step 5.

For OPT:

Initialise flag = 0;

Page 17: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 17/35

for(i=0 ; i<totalpages; i++)

{

if (table[ppage-1][i] is not empty && table[ppage-1][i] = = input[i])

set flag = 1; //Requested page is already in table so no page fault

}

if(flag = = 0){

Set flag2 = 0; // 

for(i=1; i<totalframes; i++)

{ if(table[ppage-1][i] is empty)

{

table[ppage][i]=input[ppage];

flag2=1; //No page fault as requested page already in table

break;

}

}

if(flag2 = = 0) //Page Fault has occurred; choose replacement pageGet the index of page that won’t be used for the longest time in future from current

 ppage 

}

For all other non-empty (not -1) table[][] entries, copy contents of table[ppage - 1][] to

table[ppage][].

Increment ppage by 1.

Repeat all above steps for OPT until ppage = = totalpages.

For LRU:

Initialise flag = 0;

for(i=0 ; i<totalpages; i++)

{

if (table[ppage-1][i] is not empty && table[ppage-1][i] = = input[i])

set flag = 1; //Requested page is already in table so no page fault

}

if(flag = = 0)

{

Set flag2 = 0; // 

for(i=1; i<totalframes; i++)

{ if(table[ppage-1][i] is empty)

{

table[ppage][i]=input[ppage];flag2=1; //No page fault as requested page already in table

break;

}

}

if(flag2 = = 0) //Page Fault has occurred; choose replacement page

Get the index of page that has not been used for the longest time in the past current

 ppage 

}

For all other non-empty (not -1) table[][] entries, copy contents of table[ppage - 1][] to

table[ppage][].

Increment ppage by 1.Repeat all above steps for LRU until ppage = = totalpages.

Page 18: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 18/35

For Clock:

Initialise use_bit[0] = 1 with its size equivalent to number of frames, flag = 0.

for(i=0 ; i<totalframes; i++)

{

if (table[ppage-1][i] is not empty && table[ppage-1][i] = = input[i])

set flag = 1; //Requested page is already in table so no page fault}

If the flag is 0, then check use_bit. If it is 0, replace the Page table entry otherwise set that

use_bit entry to 0 and proceed to next Page table entry checking its use_bit value in a cyclical

manner.

Increment ppage by 1.

Repeat all above steps for Clock until ppage = = totalpages.

For calculating PFaults:

Initialise pgFaults = 0.

For all page table entries starting from the first,

if(previous page table entry ! = current page table entry)

pgFaults++ ;

Display table[][] along with Page Faults for each of the above algorithms.

STOP.

PROGRAM:FCFS:#include<stdio.h>#include<conio.h>void main(){

int i,j,lastRep=-1,np,*ps,nf,*f,pf=0;clrscr();printf("Enter no of pages : ");scanf("%d",&np);

ps=(int *)malloc(sizeof(int)*np);printf("Enter page sequence : ");for(i=0;i<np;i++)

scanf("%d",&ps[i]);

printf("Enter number of frames : ");scanf("%d",&nf);f=(int *)malloc(sizeof(int)*nf);for(i=0;i<nf;i++)

f[i]=0;

for(i=0;i<np;i++){

for(j=0;j<nf;j++)if(ps[i]==f[j])

break;if(j==nf){

pf++;

Page 19: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 19/35

if(lastRep==nf-1)lastRep=0;

elselastRep++;

f[lastRep]=ps[i];

}printf("\n%d ",ps[i]);for(j=0;j<nf;j++)

printf("%d ",f[j]);}printf("\n\nNo of page faults = %d",pf);

getch();}Optimal:

#include<stdio.h>#include<conio.h>void main(){

int i,j,lastRep,np,*ps,nf,*f,pf=0,*temp,k,max;clrscr();printf("Enter no of pages : ");scanf("%d",&np);

ps=(int *)malloc(sizeof(int)*np);printf("Enter page sequence : ");

for(i=0;i<np;i++)scanf("%d",&ps[i]);

printf("Enter number of frames : ");scanf("%d",&nf);f=(int *)malloc(sizeof(int)*nf);temp=(int *)malloc(sizeof(int)*nf);for(i=0;i<nf;i++)

f[i]=0;

for(i=0;i<np;i++)

{for(j=0;j<nf;j++)

if(ps[i]==f[j])break;

if(j==nf){

pf++;for(j=0;j<nf;j++){

for(k=i+1;k<np;k++){

if(f[j]==ps[k]){

Page 20: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 20/35

temp[j]=k;break;

}}if(k==np)

temp[j]=np;}max=temp[0];lastRep=0;for(j=1;j<nf;j++)

if(temp[j]>max){

max=temp[j];lastRep=j;

}f[lastRep]=ps[i];

}printf("\n%d ",ps[i]);for(j=0;j<nf;j++)

printf("%d ",f[j]);}printf("\n\nNo of page faults = %d",pf);

getch();}

LRU:

#include<stdio.h>#include<conio.h>

int *p, *f,*temp , nof,nop;void lru();

void main(){

int i;clrscr();printf("\nEnter the Number of pages:");

scanf("%d",&nop);p=(int *)malloc(sizeof(int) * nop);printf("\nEnter the page sequence:");for(i=0;i<nop;i++)

scanf("%d",&p[i]);printf("\nEnter the Number of frames:");scanf("%d",&nof);f=(int *)malloc(sizeof(int)*nof);

temp=(int *)malloc(sizeof(int) * nof);for(i=0;i<nof;i++)

{f[i]=0;

Page 21: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 21/35

temp[i]=0;}lru();getch();

}void lru(){

int i=0,j=0,k=0,min,minindex;int pf=0;for(i=0;i<nop;i++){

for(j=0;j<nof;j++){

if(f[j]==p[i])break;

}if(j==nof){

pf++;for(j=0;j<nof;j++){

for(k=i-1;k>=0;k--){

if(f[j]==p[k]){

temp[j]=k;

break;}

}if(k==-1)

temp[j]=-1;}min=temp[0];minindex=0;for(j=1;j<nof;j++){

if(min>temp[j])

{min=temp[j];minindex=j;

}}f[minindex]=p[i];

}printf("\n%d\t",p[i]);for(j=0;j<nof;j++)

printf("%d ",f[j]);

}printf("\nNumber of page faults= %d",pf);

Page 22: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 22/35

}

Clock:

#include<stdio.h>

#include<conio.h>

int *p, *f,*used , nof,nop;void clock();

void main(){

int i;clrscr();printf("\nEnter the Number of pages:");scanf("%d",&nop);

p=(int *)malloc(sizeof(int) * nop);printf("\nEnter the page sequence:");for(i=0;i<nop;i++)

scanf("%d",&p[i]);printf("\nEnter the Number of frames:");scanf("%d",&nof);f=(int *)malloc(sizeof(int)*nof);

used=(int *)malloc(sizeof(int) * nof);for(i=0;i<nof;i++){

f[i]=0;used[i]=0;

}clock();getch();

}

void clock(){

int i,j,k;

int ptr=0;int pf=0;

for(i=0;i<nop;i++){

for(j=0;j<nof;j++){

if(p[i]==f[j]){

if(used[j]==0)used[j]=1;

break;}

Page 23: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 23/35

}

if(j==nof){

pf++;

while(1){

if(used[ptr]==0){

used[ptr]=1;f[ptr]=p[i];ptr=(ptr+1)%nof;break;

}else

used[ptr]=0;

ptr=(ptr+1)%nof;}

}printf("\n%d\t",p[i]);for(j=0;j<nof;j++)

printf("%d/%d ",f[j],used[j]);}

printf("\n\nNo of page faults = %d",pf);}

OUTPUT:

 

Page 24: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 24/35

Disk SchedulingAIM: Write a program that implements Disk Scheduling algorithms.

THEORY:

The performance of disk storage subsystem is of vital concern, and much research has

gone into schemes for improving that performance. The various algorithms include:

First-In-First-Out (FIFO): This is the simplest form of scheduling. In this, items are

processed from the queue in sequential order. This strategy has the advantage of being fair,

because every request is honored and the requests are honored in the order received.

Shortest Service Time First (SSTF): The SSTF policy is to select the disk I/O request that

requires the least movement of the disk arm from its current position. Thus, we always

choose to incur the minimum seek time. Of course, always choosing the minimum seek time

does not guarantee that the average seek time over a number of arm movements will be

minimum. However, this should provide better performance than FIFO.

SCAN: With SCAN, the arm is required to move in one direction only, satisfying all

outstanding requests en route, until it reaches the last track in that direction or until there areno more requests in that direction. The service direction is then reversed and the scan

proceeds in the opposite direction, again picking up all requests in order.

Circular SCAN (C-SCAN): This policy restricts scanning to one direction only. Thus, when

the last track has been visited in one direction, the arm is returned to the opposite end of the

disk and the scan begins again. This reduces the maximum delay experienced by new

requests.

LOGIC: (Assumption: Disk head moves in forward direction by default i.e. in direction of 

increasing/outer track numbers.)

START.

Accept the starting track number and the track requests from the user.For FCFS:

Display next track accessed based on order of appearance (in sequential order) of track 

requests entered by the user.

For SSTF:

Create an array sstf[].

This array contains integer values equivalent to the difference between current_request and

all other requests

Select the smallest value from sstf[] and find corresponding disk_request.

current_request = disk_request

If there are more disk_requests then GOTO step (ii).

For SCAN:Display track requests after starting track number in ascending order of requests until last

track in forward direction has been displayed.

Display track requests before starting track number in descending order of requests until last

track in backward direction has been displayed.

For C-SCAN:

Display track requests after starting track number in ascending order of requests until last

track in forward direction has been displayed.

Reset the disk head to start of the track and again display in ascending order of requests until

the starting track is reached.

Display table for the chosen algorithm containing Next Track Accessed, Total Seek Length

and the Average Seek Length for that algorithm.

STOP.

Page 25: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 25/35

 

PROGRAM:

#include<stdio.h>#include<conio.h>

#include<math.h>

#define SIZE 20void fifo();void sstf();void scan();void cscan();int req[SIZE],no_track, th,no_req;

void main(){

int ch,i;clrscr();printf("\nEnter the number of requests:");scanf("%d",&no_req);printf("\nEnter the request sequence:\n");for(i=0;i<no_req;i++)

scanf("%d",&req[i]);printf("\nEnter the Track Head Position:\n");

scanf("%d",&th);do{

printf("\nSelect from Following: ");

printf("\n1: FIFO");printf("\n2: SSTF");printf("\n3: SCAN");printf("\n4: CSCAN");printf("\n5: EXIT");printf("\nEnter your choice:");scanf("%d",&ch);switch(ch){

case 1: fifo();break;

case 2: sstf();break;

case 3: scan();break;

case 4: cscan();break;

}}while(ch!=5);

}

Page 26: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 26/35

void fifo(){

int i,sum=0,track_head;float avg;track_head=th;

printf("\t------FIFO------");printf("\nNext Track\t\tNo of Tracks\n");for(i=0;i<no_req;i++){

no_track=abs(track_head-req[i]);printf("%d\t\t\t%d\n",req[i],no_track);sum=sum+no_track;track_head=req[i];

}avg=((float)sum/(float)no_req);printf("\nTotal= %d\nAverage= %.2f",sum,avg);

}

void sstf(){

inti,sum=0,min=0,new_track=1000,min_head=0,ctr=0,track_head;

int access[SIZE];track_head=th;for(i=0;i<no_req;i++)

access[i]=0;float avg;

printf("\t------SSTF------");printf("\nNext Track\t\tNo of Tracks\n");while(ctr!=no_req){

for(i=0;i<no_req;i++){

if(access[i]==0){

no_track=abs(track_head-req[i]);if(new_track>no_track) //checks for

the lowest traversal

{new_track=no_track; //gets the new

lowestmin=req[i]; //gets the corr

elementmin_head=i; //corr position

}}

}

printf("%d\t\t\t%d\n",min,new_track); //lowest

element and tracks traversedsum=sum+new_track;

Page 27: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 27/35

new_track=1000;access[min_head]=1;track_head=min;ctr++;

}

avg=((float)sum/(float)no_req);printf("\nTotal= %d\nAverage= %.2f",sum,avg);

}void scan(){

inti,sum=0,min=0,new_track=1000,min_head=0,ctr=0,track_head;

int max=req[0],flag=0;int access[SIZE];track_head=th;for(i=0;i<no_req;i++)

access[i]=0;for(i=0;i<no_req;i++){

if(max<req[i])max=req[i];

}float avg;printf("\t------SCAN------");printf("\nNext Track\t\tNo of Tracks\n");while(ctr!=no_req)

{for(i=0;i<no_req;i++){

if(access[i]==0){

no_track=abs(track_head-req[i]);if(flag==0){

if(track_head<req[i] &&new_track>no_track) //checks for the lowest traversal

{

new_track=no_track; //gets thenew lowest

min=req[i]; //gets thecorr element

min_head=i; //corr position}if(track_head==max){

new_track=new_track+abs(max-th);track_head=th;flag=1;

}

Page 28: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 28/35

}else{

if(new_track>no_track) //checksfor the lowest traversal

{

new_track=no_track; //gets thenew lowest

min=req[i]; //gets thecorr element

min_head=i; //corr position}

}}

}if(track_head==th && ctr>0)

new_track+=abs(max-th);printf("%d\t\t\t%d\n",min,new_track); //lowest

element and tracks traversedsum=sum+new_track;// if(track_head==th)

// sum=sum+ abs(max-th);new_track=1000;access[min_head]=1;track_head=min;

ctr++;}avg=((float)sum/(float)no_req);printf("\nTotal= %d\nAverage= %.2f",sum,avg);

}

void cscan(){

inti,sum=0,min=0,new_track=1000,min_head=0,ctr=0,track_head;

int max=req[0],mini=req[0];int access[SIZE];track_head=th;for(i=0;i<no_req;i++)

access[i]=0;for(i=0;i<no_req;i++){

if(max<req[i])max=req[i];

if(mini>req[i])mini=req[i];

}

Page 29: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 29/35

float avg=0.0;printf("\t------CSCAN------");printf("\nNext Track\t\tNo of Tracks\n");while(ctr!=no_req){

for(i=0;i<no_req;i++){

if(access[i]==0){

no_track=abs(track_head-req[i]);if(track_head<req[i] &&

new_track>no_track) //checks for the lowest traversal{

new_track=no_track; //gets thenew lowest

min=req[i]; //gets the

corr elementmin_head=i; //corr position

}if(track_head==max){

track_head=0;

}

}}

if(track_head==0)new_track=abs(max-mini);

printf("%d\t\t\t%d\n",min,new_track); //lowestelement and tracks traversed

sum=sum+new_track;new_track=1000;access[min_head]=1;track_head=min;ctr++;

}avg=((float)sum/(float)no_req);

printf("\nTotal= %d\nAverage= %.2f",sum,avg);

}

Page 30: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 30/35

OUTPUT:

Page 31: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 31/35

Resident Set ManagementAIM: Write a program that implements Resident Set

THEORY: This program combines process scheduling with page replacement and uses equal

frame allocation for each process.

PROGRAM:package resident.set;import java.io.*;class Process{

char name;int cnt, at, st, ft ,tr;int pages[];

}

public class ResidentSet{Process p[];int processcount;BufferedReader br=new BufferedReader(new

InputStreamReader(System.in));int frames[],noofframes, pf[];char pagefault[];

public void accept() throws Exception{

System.out.println("Enter number of processes: ");processcount = Integer.parseInt(br.readLine());p= new Process[processcount];for(int i=0; i<processcount;i++){

p[i]= new Process();p[i].name =(char)(65+i);System.out.print("Enter arrival time :");

p[i].at = Integer.parseInt(br.readLine());System.out.print("Enter service time :");

p[i].st = Integer.parseInt(br.readLine());int cnt = p[i].st;p[i].pages = new int[cnt];System.out.print("Enter pages for process

"+p[i].name);for(int j=0; j<cnt; j++){

p[i].pages[j] =Integer.parseInt(br.readLine());

}

}System.out.print("Enter number of frames : ");

Page 32: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 32/35

noofframes =Integer.parseInt(br.readLine());frames = new int[processcount * noofframes];

initialize();

}

public void initialize(){

int total=0;

for(int i=0; i<processcount ; i++){

total+=p[i].st;}pagefault = new char[total];

}

public void fifo(){

float ratio[]=new float[p.length];int i,temp=0;

int n=p.length;for(i=0;i<n;i++){

temp=temp+p[i].st;p[i].ft=temp;if(i==0)

p[i].tr=p[i].ft;else

p[i].tr=p[i-1].ft-p[i].at+p[i].st;}for(i=0;i<n;i++){

ratio[i]=(float)p[i].tr/p[i].st;}System.out.println("Process\tArrival time\tService

time\tFinish time\tTurnaround time\ttr\\ts");for(i=0;i<n;i++)

{System.out.println((i+1)+"\t "+p[i].at+"\t

"+p[i].st+"\t " +p[i].ft+"\t "+p[i].tr+"\t"+ratio[i]);

}}

public void fifop(){

boolean flag= true;

int currentptr=0;pf=new int[p.length];

Page 33: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 33/35

int s=0;for(int a=0; a<processcount;a++){

int temp=a*noofframes;currentptr = temp;

for(int b=0; b<p[a].st; b++){

for(int k=temp; k<temp+noofframes;k++)

{if(p[a].pages[b] == frames[k]){

flag=false;break;

}else

flag=true;}

if(flag){

frames[currentptr++]= p[a].pages[b];pf[a]++;

}if(currentptr == noofframes*a+noofframes)

currentptr=noofframes*a;

displayframe();

}

}

}public void displayframe(){

for(int row=0; row<processcount * noofframes;row++){

if(row%noofframes==0)

System.out.printf(" || ");System.out.printf("%6d",frames[row]);

}

System.out.println();

}public void printFaults(){

for(int a=0;a<processcount;a++){

Page 34: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 34/35

System.out.println("Page Faults in Process"+p[a].name+ " are "+pf[a]);

}}public static void main(String[] args) throws Exception

{ResidentSet rs = new ResidentSet();rs.accept();rs.fifo();rs.fifop();rs.displayframe();rs.printFaults();}

Page 35: OS Practs Fin

7/31/2019 OS Practs Fin

http://slidepdf.com/reader/full/os-practs-fin 35/35

OUTPUT:

Enter number of processes:

4

Enter arrival time :2

Enter service time :3Enter pages for process A1

2

3

Enter arrival time :3

Enter service time :3

Enter pages for process B1

2

3

Enter arrival time :5

Enter service time :2

Enter pages for process C12

Enter arrival time :7

Enter service time :1

Enter pages for process D1

Enter number of frames : 3

Process Arrival time Service time Finish time Turnaround time tr\ts

1 2 3 3 3 1.0

2 3 3 6 3 1.0

3 5 2 8 3 1.5

4 7 1 9 2 2.0

|| 1 0 0 || 0 0 0 || 0 0 0 || 0 0 0

|| 1 2 0 || 0 0 0 || 0 0 0 || 0 0 0

|| 1 2 3 || 0 0 0 || 0 0 0 || 0 0 0

|| 1 2 3 || 1 0 0 || 0 0 0 || 0 0 0

|| 1 2 3 || 1 2 0 || 0 0 0 || 0 0 0

|| 1 2 3 || 1 2 3 || 0 0 0 || 0 0 0

|| 1 2 3 || 1 2 3 || 1 0 0 || 0 0 0

|| 1 2 3 || 1 2 3 || 1 2 0 || 0 0 0

|| 1 2 3 || 1 2 3 || 1 2 0 || 1 0 0

|| 1 2 3 || 1 2 3 || 1 2 0 || 1 0 0

Page Faults in Process A are 3Page Faults in Process B are 3

Page Faults in Process C are 2

Page Faults in Process D are 1