0% found this document useful (0 votes)
14 views70 pages

(CN & Os) Final Lab Manual

The document outlines the simulation of various CPU scheduling algorithms including Round Robin, Shortest Job First (SJF), First Come First Served (FCFS), and Priority. Each algorithm is described with its scheduling type, explanation, source code, and sample input/output. The conclusions highlight the advantages and operational mechanisms of each scheduling method.

Uploaded by

sreevs749
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views70 pages

(CN & Os) Final Lab Manual

The document outlines the simulation of various CPU scheduling algorithms including Round Robin, Shortest Job First (SJF), First Come First Served (FCFS), and Priority. Each algorithm is described with its scheduling type, explanation, source code, and sample input/output. The conclusions highlight the advantages and operational mechanisms of each scheduling method.

Uploaded by

sreevs749
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 70

1

Practical – 1
ROUND ROBIN

Problem: 1. Simulate the following CPU scheduling algorithms


a)Round Robin b) SJFc) FCFSd) Priority
Aim: To simulate Round Robin CPU scheduling algorithm

Problem description:

A CPU scheduling algorithm determines an order for the execution of its


scheduled processes. Scheduling Types
1. Pre-emptive scheduling
2. Non pre-emptive scheduling
Pre-emptive scheduling allows a process to be interrupted in the midst of its execution, taking
the CPU away and allocating it to another process. Non pre-emptive scheduling ensures that a
process relinquishes control of the CPU only when it finishes with its current CPU burst

CPU-scheduling algorithms are parameterized as.


ROUND ROBIN (RR)
SHORTEST JOB FIRST (SJF)
FIRST COME FIRST SERVERD (FCFS)
PRIORITY

Explanation:
<

Uses preemption based on a clock,An amount of time is determined that allows each
process to use the processor for that length of time. Clock interrupt is generated at periodic
intervals. When an interrupt occurs, the currently running process is placed in the read queue-
Next ready job is selected. This is Known as time slicing

Source code:
Simulation of Round Robin Scheduling Algorithm
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,m,n,n1,n2,svt,stat,slice,in[20];
2

float atat,antat,sntat,ntat[20];
char p[20];
int at[20],st[20],st1[20],wt[20],ft[20],tat[20],min;
clrscr();
printf("Enter the number of processes and slice");
scanf("%d%d",&n,&slice);
m=n;
for(i=0;i<n;i++)
{
printf("\n Enter process arrival time and service time");
scanf("%d%d",&at[i],&st[i]);
in[i]=i;
st1[i]=st[i];
p[i]=(char)('A'+i);
}
svt=0;
stat=0;
sntat=0.0;
j=0;
n1=n;n2=n;i=0;
while(n!=0)
{
n=n1;
n1=0;
j=0;
for(i=0;i<n;i++)
{
if(st[in[i]]<=slice)
{
svt+=st[in[i]];
ft[in[i]]=svt;
}
else
{
svt+=slice;
st[in[i]]-=slice;
3

in[j]=in[i];
j++;
n1++;
}
}
}
for(i=0;i<n2;i++)
{
tat[i]=ft[i]-at[i];
ntat[i]=(float)tat[i]/st1[i];
stat+=tat[i];
sntat+=ntat[i];
atat=(float)stat/m;
antat=(float)sntat/m;
} printf("\n%s\t%s\t%s\t%s\t%s\t%s","proc","at","st","ft","tat","ntat");
for(i=0;i<n2;i++)
{ printf("\n%c\t%d\t%d\t%d\t%d\t%f",p[i],at[i],st1[i],ft[i],tat[i],ntat[i]);
}
printf("\naverage turnaround time and normalized turnaround time");
printf("%f\t%f",atat,antat);
getch();
return 0;
}

Conclusion:
It is a straight forward way to reduce the penalty that short jobs suffer with fcfs .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 job is selected on FCFS basis. This
is called time slicing. Here same formulas are used as in fcfs but are want to consider slice
time for the each process.
4

Sample Input and Output :


Enter the number of processes and slice 5 4
Enter process arrival time and service time 0 3
Enter process arrival time and service time 2 6
Enter process arrival time and service time 4 4
Enter process arrival time and service time 6 5
Enter process arrival time and service time 8 2

proc at st ft tat ntat


A 0 3 3 3 1.000000
B 2 6 19 17 2.833333
C 4 4 11 7 1.750000
D 6 5 20 14 2.800000
E 8 2 17 9 4.500000

Average turnaround time and normalized turnaround time10.000000 2.576667


5

SHORTEST JOB FIRST

Problem: 1. Simulate the following CPU scheduling algorithms

a) Round Robin b) SJF c) FCFS d) Priority

Aim: To simulate SJF CPU scheduling algorithm

Problem description:
A CPU scheduling algorithm determines an order for the execution of its
scheduled processes. Scheduling Types
1.Preemptive scheduling
2.Nonpreemptive scheduling
Preemptive scheduling allows a process to be interrupted in the midst of its execution,
taking the CPU away and allocating it to another process. Nonpreemptive scheduling
ensures that a process relinquishes control of the CPU only when it finishes with its
current CPU burst
CPU-scheduling algorithms are parameterized as.
ROUND ROBIN (RR)
SHORTEST JOB FIRST (SJF)
FIRST COME FIRST SERVERD (FCFS)
PRIORITY

Explanation:
Predictability of longer processes is reduced.If estimated time for process not correct; the
operating system may abort it. There is a possibility of starvation for longer processes
Source code:
Simulation of Shortest Job First CPU Scheduling Algorithm
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,n,pos,count,count1,svt,stat,serviced[20];
float atat,antat,sntat,ntat[20];
char p[20];
6

int at[20],st[20],wt[20],ft[20],tat[20],min;
clrscr();
printf("Enter the number of processes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the process arrival time and service time");
scanf("%d%d",&at[i],&st[i]);
serviced[i]=0;
p[i]=(char)('A'+i);
}
svt=0;
count=0;
stat=0;
sntat=0.0;j=0;
while(count<n)
{
count1=0;
for(i=0;i<n;i++)
{
if((at[i]<=svt) && (serviced[i]==0))
{
if (count==0)
{
min=st[0];
pos=0;
}
else
{
count1++;
if(count1==1)
{
pos=i;
min=st[i];
}
else if(st[i]<=min)
7

{
pos=i;
min=st[i];
}
}
}
}
count++;
svt+=st[pos];
ft[pos]=svt;
tat[pos]=ft[pos]-at[pos];
ntat[pos]=(float)tat[pos]/st[pos];
stat+=tat[pos];
sntat+=ntat[pos];
serviced[pos]=1;
j++;
}
atat=(float)stat/n;
antat=(float)sntat/n;
printf("\n %s\t%s\t%s\t%s\t%s\t%s","Proc","AT","ST","FT","TAT","NTAT");
for(i=0;i<n;i++)
{
printf("\n %c\t%d\t%d\t%d\t%d\t%f",p[i],at[i],st[i],ft[i],tat[i],ntat[i]);
}
printf("\n %s %f %f"," Avg turnaround time and Average normalized turnaround
time",atat,antat);
getch();
}

Conclusion
In the shortest job first algorithm, processes are executed on the basis of their service
time. each process is given a service time. After the completion of execution of current
process depending on service times of process i.e,process which is having last service time is
executed next, this procedure is repeated until completion then finishing times, turnaround
time and its average are calculated.
8

Sample I/P and O/P:


Enter the number of processes 5
Enter the process arrival time and service time 0 3
Enter the process arrival time and service time 2 6
Enter the process arrival time and service time 4 4
Enter the process arrival time and service time 6 5
Enter the process arrival time and service time 8 2

Proc AT ST FT TAT NTAT


A 0 3 3 3 1.000000
B 2 6 9 7 1.166667
C 4 4 15 11 2.750000
D 6 5 20 14 2.800000
E 8 2 11 3 1.500000
Avg turnaround time and Average normalized turnaround time 7.600000 1.843333
9

FIRST COME FIRST SERVED

Problem: 1. Simulate the following CPU scheduling algorithms


a) Round Robin b) SJF c) FCFS d) Priority
Aim: To simulate FCFS CPU scheduling algorithm

Problem description:
A CPU scheduling algorithm determines an order for the execution of its
scheduled processes. Scheduling Types
1.Preemptive scheduling
2.Nonpreemptive scheduling
Preemptive scheduling allows a process to be interrupted in the midst of its execution, taking
the CPU away and allocating it to another process. Nonpreemptive scheduling ensures that a
process relinquishes control of the CPU only when it finishes with its current CPU burst
CPU-scheduling algorithms are parameterized as.
ROUND ROBIN (RR)
SHORTEST JOB FIRST (SJF)
FIRST COME FIRST SERVERD (FCFS)
PRIORITY

Explanation:

Each process joins the Ready queue.When the current process ceases to execute, the oldest
process in the Ready queue is selected.A short process may have to wait a very long time
before it can execute.This algorithm Favors CPU-bound processes.I/O processes have to wait
until CPU-bound process completes

Source code:

Simulation of FCFS CPU Scheduling Algorithm


#include<stdio.h>
#include<conio.h>
int main()
{
int at[20],st[20],wt[20],ft[20],tat[20];
int n,i,j,nstat,svt;
10

char p[20];
float
at,astat,antat,ntat[20],stat=0.0,sntat=0.0;
clrscr();
printf("Enter number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process arrival time and service time");
scanf("%d%d",&at[i],&st[i]);
}
svt=0;
for(i=0;i<n;i++)
{
svt += st[i];
ft[i]=svt;
tat[i]=ft[i]-at[i];
wt[i]=ft[i]-(at[i]+st[i]);
ntat[i]=(float)tat[i]/st[i];
stat += tat[i];
sntat += ntat[i];
p[i]=(char)('A'+i);
}
atat =(float)stat/n;
antat=(float)sntat/n;
printf("\nPr\tAt\tst\twt\tft\ttat\tntat");
for(i=0;i<n;i++)
{
printf("\n %c\t%d\t%d\t%d\t%d\t%d\t%f",
p[i],at[i],st[i],wt[i],ft[i],tat[i],ntat[i]);
}
printf("\n%s %f %f ","Average tat and ntat are ",atat,antat);
}
11

Conclusion
The simplest scheduling policy is First-Come First Served, also known as first-
in_first_out(FIFO).As each process become 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.

Sample I/P and O/P:

Enter number of processes: 4


enter process arrival time and service time 0 7
enter process arrival time and service time 1 4
enter process arrival time and service time 3 2
enter process arrival time and service time 5 5

Pr At st wt ft tat ntat
A 0 7 0 7 7 1.000000
B 1 4 6 11 10 2.500000
C 3 2 8 13 10 5.000000
D 5 5 8 18 13 2.600000
Average tat and ntat are 10.000000 2.775000
12

PRIORITY

Problem: 1. Simulate the following CPU scheduling algorithms


a) Round Robin b) SJF c) FCFS d) Priority

Aim: To simulate Priority CPU scheduling algorithm

Problem description:
A CPU scheduling algorithm determines an order for the execution of its
scheduled processes. Scheduling Types
1.Preemptive scheduling
2.Nonpreemptive scheduling
Preemptive scheduling allows a process to be interrupted in the midst of its execution, taking
the CPU away and allocating it to another process. Nonpreemptive scheduling ensures that a
process relinquishes control of the CPU only when it finishes with its current CPU burst
CPU-scheduling algorithms are parameterized as.
ROUND ROBIN (RR)
SHORTEST JOB FIRST (SJF)
FIRST COME FIRST SERVERD (FCFS)
PRIORITY

Explanation:

In this algorithm priority and service time of processes are given.First the process is
executed.after completition of current process,process which is having least priority is
executed next and so on upto least,process then finishing, turn around and average turn
around time is calculated.

Source code
Source Code of Priority CPU scheduling Algorithm
#include<stdio.h>
main()
{
char p[10];
int at[10],pr[10],st[10];
13

int ft[10],tat[10],i,j,t[10],n,x,wt[10];
int p1[10],a1[10],s1[10];
float ntat[10],stat=0.0,sntat=0.0,atat=0.0,antat=0.0;
clrscr();
printf("Enter the number of Processes");
scanf("%d",&n);

printf("\n Enter Process Names");


for(i=0;i<n;i++)
scanf(" %c",&p[i]);

printf("\n Enter the Arrival times");


for(i=0;i<n;i++)
{
scanf("%d",&at[i]);
a1[i]=at[i];
}
printf("\n Enter Priorities");
for(i=0;i<n;i++)
{
scanf("%d",&pr[i]);
p1[i]=pr[i];
}
printf("\n Enter Service time");
for(i=0;i<n;i++)
{
scanf("%d",&st[i]);
s1[i]=st[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n-1;j++)
if(p1[i]>p1[j])
{
x=p1[i];
p1[i]=p1[j];
14

p1[j]=x;

x=s1[i];
s1[i]=s1[j];
s1[j]=x;

x=a1[i];
a1[i]=a1[j];
a1[j]=x;

}
}

tat[0]=0;
for(i=0;i<n;i++)
{
if(i==0)
{
ft[i]=a1[i]+s1[i];
}
else
{
ft[i]=s1[i]+ft[i-1];
}
wt[i]=ft[i]-(s1[i]+a1[i]);
tat[i]=ft[i]-a1[i];
ntat[i]=tat[i]/s1[i];
stat+=tat[i];
sntat+=ntat[i];
}
atat=stat/(float)(n);
antat=sntat/(float)(n);
printf("\npro at pr st ft wt tat ntat\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
15

if(pr[i]==p1[j])
printf("\n%3c%3d%3d%3d%3d%3d%3d %.3f",p[i],at[i],pr[i],st[i],ft[i],wt[i],tat[i],ntat[i]);
}
printf("\nAvg tat=%f \nAvg Ntat=%f",atat,antat);
getch();
}

Conclusion:

In this algorithm priority and service time of processes are given.First the process is
executed.after completition of current process,process which is having least priority is
executed next and so on upto least,process then finishing, turn around and average turn
around time is calculated.

Sample I/P and O/P:


pro at pr st ft wt tat ntat
A 0 3 3 6 0 6 1.000
B 0 1 6 11 6 11 2.000
C 0 4 4 14 11 14 4.000
D 0 2 5 18 14 18 4.000
E 0 5 2 20 18 20 10.000
Avg tat=13.800000
Avg Ntat=4.200000
16

Practical – 2
FIFO
Problem Simulate all page replacement algorithms
a) FIFO b) LRU c) LFU Etc.
Aim: To simulate FIFO page replacement algorithm.
Problem description:

The FIFO policy treats the page frame allocated to a process as a circular buffer and pages
are removed in round robin fashion or style. All pages that is required in a pointer that circles
through the page frames if the process. This is therefore one of the simplest page replacement
policies to implement. The page that has been in memory the largest is replaced, also the page
faults are calculated.

Explanation:

Treats page frames allocated to a process as a circular buffer.Here Pages are removed in
round-robin style.This is the Simplest replacement policy to implement.The Page that has
been in memory the longest is replaced. These pages may be needed again very soon

Example:

Assume a fixed frame allocation for 3 frames the reference string is 232152453252. First
the page 2 is replaced in first frame and then 3 in second page 200, 230. The frame
for pages of process 2 is already allocated so, when 2 come again it is in the frame allocated
to process 2 is taken by it. Now when the process 1 comes the page frame becomes as
231 and the page faults become as 3.

When fifth process page is ready to replace a page in the 3 frames and the page fault is
incremented by 1. As the process page 2 is for longest time now it is replaced by the 5 th
process page i.e., 531.

This process is repeated until the reference string pages are placed onto the frames, then
finally 352 are the process pages in the frame.

Solution steps:

1. The given memory is divided into frames of equal to page size.


2. The reference string is taken.
3. Arrange the pages in frames.
17

4. Rest of pages in the reference strin


are placed in the frame by applying FIFO page in replacement policy
5. After replacing each page note that the fault at page.
6. Repeat steps 3, 4 & 5.
Source code:

Simulation of FIFO Page Replacement Algorithm


#include<stdio.h>
#include<conio.h>
int str[30],z,count,fs,p[100],pf=0;
main()
{
int i,j,k,temp;
printf("\n Enter the No.of frames:");
scanf("%d",&fs);
printf("\n Enter string (-1 to stop):");
i=0;
while(1)
{
scanf("%d",&temp);
if(temp==-1)
break;
str[i++]=temp;
}
count=i;
for(i=0;i<fs;i++)
p[i]=-1;
printf("\n\t Pages \t Frames");
i=j=0;
while(i<count)
{
if(!check(str[i]))
{
pf++;
p[j]=str[i];
j=(j+1)%fs;
18

}
printf("\n\t <%d> \t",str[i]);
for(k=0;k<fs;k++)
if(p[k]!=-1)
printf("%3d",p[k]);
i++;
}
z=pf-fs;
printf("\n\t Page Faults:%d",z);
}
check(int key)
{
int i;
for(i=0;i<fs;i++)
if(key==p[i])
return 1;
return 0;
}

Conclusion:

Treats page frames allocated to a process as a circular buffer.Here Pages are removed in
round-robin style.This is the Simplest replacement policy to implement.The Page that has
been in memory the longest is replaced. These pages may be needed again very soon

Sample I/P and O/P:


1) Enter the No.of frames:3
Enter string (-1 to stop):2 3 2 1 5 2 4 5 3 2 5 2 -1
Pages Frames
<2> 2
<3> 2 3
<2> 2 3
<1> 2 3 1
<5> 5 3 1
<2> 5 2 1
<4> 5 2 4
19

<5> 5 2 4
<3> 3 2 4
<2> 3 2 4
<5> 3 5 4
<2> 3 5 2
Page Faults:6

Enter the No.of frames:3

2)Enter string (-1 to stop):6 2 4 5 8 9 1 2 6 -1

Pages Frames
<6> 6
<2> 6 2
<4> 6 2 4
<5> 5 2 4
<8> 5 8 4
<9> 5 8 9
<1> 1 8 9
<2> 1 2 9
<6> 1 2 6
Page Faults:
20

LRU

Problem: Simulate all page replacement algorithms


a) FIFO b) LRU c) LFU Etc.
Aim: To simulate LRU page replacement algorithm.
Problem description:

The LRU policy replaces the paging memory that has not been referenced for the longest time. By the
principle of locality this should be the page that least likely to be referenced in the near future and
infect LRU policy does not nearly as well as the optimal policy. Its implementation is difficult.

Explanation:

This algorithm replaces the page that has not been referenced for the longest time. This algorithm
works on the principle of principle of locality by the principle of locality, this should be the page
least likely to be referenced in the near future.Each page could be tagged with the time of last
reference. This would require a great deal of overhead.

Example:

Consider the fixed frame allocation of 3 frames. The page address stream be 2321523152. The first 2
are placed in frames and the 1 is also placed in the 3 rd frame like it will be 231.Like that least
recently used value will be placed with new value and for every replacement page fault is counted.

Solution steps:

1. Read number of frames and number of pages in reference string.


2. Read reference string.
3. Arrange the pages in frames.
4. Rest of pages in the reference string are placed in the frame by applying LRU page in
replacement policy
5. After replacing each page note that the fault at page.
6. Repeat steps 3, 4 & 5.
21

Source code:

Simulation of LRU Page Replacement Algorithm


#include<stdio.h>
#include<conio.h>
int str[30],count,fs,p[100],pf;
main()
{
int i,j,k,z,temp;
printf("\n Enter the No.of frames:");
scanf("%d",&fs);
printf("\n Enter string (-1 to stop):");
i=0;
while(1)
{
scanf("%d",&temp);
if(temp==-1)
break;
str[i++]=temp;
}
count=i;
for(i=0;i<fs;i++)
p[i]=-1;
printf("\n Pages \t\t Frames");
i=0;
while(i<count)
{
if(!check(str[i]))
{
pf++;
j=lru(i);
p[j]=str[i];
}
printf("\n %3d \t\t",str[i]);
for(k=0;k<fs;k++)
if(p[k]!=-1)
22

printf("%3d",p[k]);
i++;
}
z=pf-fs;
printf("\n\n Page Faults:%d",z);
}
check(int key)
{
int i;
for(i=0;i<fs;i++)
if(key==p[i])
return 1;
return 0;
}
lru(int pos)
{
int i,j=0,r=0;
for(i=0;i<fs;i++)
{
if(p[i]==-1)
return i;
if(rec(i,pos)>=r)
{
j=i;
r=rec(i,pos);
} }
return j;
}
rec(int fn,int pn)
{
int i,c=0;
for(i=pn-1;i>=0;i--)
{
c++;
if(p[fn]==str[i])
return c;
23

}
}

Conclusion

This algorithm replaces the page that has not been referenced for the longest time. This
algorithm works on the principle of principle of locality by the principle of locality, this
should be the page least likely to be referenced in the near future.Each page could be tagged
with the time of last reference. This would require a great deal of overhead.

Sample I/P and O/P:

1) Enter the No. of frames: 3


Enter string (-1 to stop):2 3 2 1 5 2 4 5 3 2 5 2 -1
Pages Frames
2 2
3 2 3
2 2 3
1 2 3 1
5 2 5 1
2 2 5 1
4 2 5 4
5 2 5 4
3 3 5 4
2 3 5 2
5 3 5 2
2 3 5 2

Page Faults:4
24

Practical – 3
MVT

Problem: Simulate MVT and MFT

Aim: Simulation of Multi Programming with Variable number of Tasks algorithm. Problem
description: Subdividing memory to accommodate multiple processes.Memory needs to be
allocated to ensure a reasonable supply of ready processes to consume available processor
time

Explanation:

This is also known as unequal-size partition. This Can assign each process to the smallest
partition within which it will fit.This maintains Queue for each partition .Here Processes are
assigned in such a way as to minimize wasted memory within a partition.In this algorithm
memory partitions are created dynamically, so that each process is loaded into a partition of
exactly the same size as that of process.

Strengths:

1. No internal fragmentation.
2. More efficient use of main memory.

Weaknesses:

Inefficient use of processors due to the need for compaction to counter external
fragmentation.

Example:

Let the whole memory size is 200and length of processes is 4. Let the size for each
process is 40,30,50,60 respectively for a, s, d, f processes. Let the memory required for
Operating System is 10. Then the memory allocation is as shown in the following table:

The total External fragmentation is: 10


25

Partition Allocated memory Offset Displacement


O 10 10 10
A 40 50 40
S 30 80 30
D 50 130 50
F 60 190 60

Source Code
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char pr[20],m[20];
int a[20],d[20],ps[20],o[20],i,j,k,l,fr,w,s,z,b,os;
clrscr();
b=0;z=0;fr=0;os=10;s=0;
printf("\n Enter the process sequence:");
gets(pr);
l=strlen(pr);
printf("Length of processes:");
printf("%d",l);
printf("\nEnter the whole partition size:");
scanf("%d",&w);
printf("\nEnter the Process sizes:");
for(i=0;i<l;i++)
scanf("%d",&ps[i]);
m[0]='o';
k=1;
a[0]=10;o[0]=10;d[0]=10;
w-=10;
printf("Size of OS=%d",os);
for(i=0;i<l;i++)
{
m[k]=pr[i];
26

b=w-s;
if(ps[i]<=b)
{
s=s+ps[i];
a[k]=ps[i];
o[k]=s+os;
d[k]=ps[i];
z=k;
fr=w-s;
}
else
{
z=k-1;
fr=w-s;
z--;
}
k++;
}
printf("\nExternal Fragmentation=%d",fr);
printf("\nPartition Alloc Offset Disp");
for(i=0;i<=z;i++)
printf("\n%c \t %d \t %d \t %d",m[i],a[i],o[i],d[i]);
for(i=z;i<l;i++)
printf("\nProcess Not Allocated=%c",pr[i]);
}

Conclusion:
In this algorithm memory partitions are created dynamically, so that each process is loaded into a
partition of exactly the same size as that of process.

Sample Inputs and outputs:


Run1:
Enter the process sequence:asdf
Length of processes:4
Enter the whole partition size:200
27

Enter the Process sizes:40 30 50 60


Size of OS=10
External Fragmentation=10
Partition Alloc Offset Disp
o 10 10 10
a 40 50 40
s 30 80 30
d 50 130 50
f 60 190 60

Run2:
Enter the process sequence:pqrs
Length of processes:4
Enter the whole partition size:200
Enter the Process sizes:100 90 40 90
Size of OS=10
External Fragmentation=0
Partition Alloc Offset Disp
o 10 10 10
p 100 110 100
q 90 200 90
Process Not Allocated=r
Process Not Allocated=s
28

MFT

Problem: Simulate MVT and MFT

Aim: Simulation of Multi Programming with Fixed number of Tasks algorithm.

Problem description:

This is also called as equal-size partition algorithm.Any process whose size is less than or
equal to the partition size can be loaded into an available partition.If all partitions are full, the
operating system can swap a process out of a partition.A program may not fit in a partition.
The programmer must design the program with overlays

Explanation:

Main memory use is inefficient. Any program, no matter how small, occupies an entire
partition. This is called internal fragmentation. Main memory is divided into a number of
static partitions at system generation time. A process may be loaded into a partition of equal
or grater size.

Strengths:

1. Simple to implement.
2. Little operating system overhead.
Weaknesses:

1. Inefficient use of memory due to internal fragmentation.


2. Maximum number of active processes is fixed.
Example:

Let the whole memory size is 300and length of processes is 5. Let the size for each
process is 50, 10, 40, 20, 30 respectively for a, s, d, f, g processes. Let the whole memory is
divided into equal partition size of 50. Let the memory required for Operating System is 10.
Then the memory allocation is as shown in the following table:
29

Partition Offset Allocated memory Fragmentation


A 50 50 0
S 100 10 40
D 150 40 10
F 200 230 30
G 250 30 20

The total internal fragmentation is : 100

Source Code

#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char p[20];
int a[20],d[20],o[20],ps[20],f[20];
int i,j,n,m,l,fr,z;
clrscr();
z=0;fr=0;
printf("\nEnter the process sequence:");
gets(p);
l=strlen(p);
printf("Enter the size of the partition:");
scanf("%d",&n);
printf("\nEnter the whole partition:");
scanf("%d",&m);
printf("\nEnter the Process sizes:");
for(i=0;i<l;i++)
{
a[i]=0;d[i]=0;o[i]=10;
scanf("%d",&ps[i]);
}
for(i=0;i<l;i++)
{
30

if(ps[i]<=n)
{

d[i]=ps[i];
f[i]=n-ps[i];
z++;
}
}
for(i=1;i<l;i++)
{
o[i]=o[i-1]+n;
}
for(i=0;i<z;i++)
{
fr+=f[i];
}
printf("\nTotal Internal Fragmentation=%d \n",fr);
printf("Process Offset Disp Fragmentation");
for(i=0;i<l;i++)
{
printf("\n%c\t%d \t %d\t %d",p[i],o[i],d[i],f[i]);
}
}

Conclusion:
This algorithm is very Simple to implement.Little operating system overheads. Inefficient
use of memory due to internal fragmentation and Maximum number of active processes is
fixed are the draw backs of this algorithm.
Sample I/P and O/P:
1)Enter the process sequence:pqrs
Enter the size of the partition:40
Enter the whole partition:200
Enter the Process sizes:20 30 40 10
Total Internal Fragmentation=60
Process Offset Disp Fragmentation
31

p 10 20 20
q 50 30 10
r 90 40 0
s 130 10 30
2) Enter the process sequence:abcd
Enter the size of the partition:30
Enter the whole partition:200
Enter the Process sizes:20 30 30 10
Total Internal Fragmentation=30
Process Offset Disp Fragmentation
a 20 20 10
b 50 30 0
c 80 30 0
d 90 10 20
32

Practical – 4
Bankers Algorithm for Deadlock Avoidance

Problem: Simulate Bankers Algorithm for Dead Lock Avoidance

Aim: To simulate Bankers algorithm to avoid the attainment of Dead Lock.

Problem description:

Dead Lock is defined as the permanent blocking of a set of processes that either compete for
system resources or communicate with each other. There is no efficient solution for this and
this Involves conflicting needs for resources by two or more processes.We can say the
conditions for deadlock as

• Mutual Exclusion

• No preemption

• Hold and wait

This algorithm verifies the attainment of dead lock for the given system.

Explanation:
An approach to solving the deadlock problem that differs subtly from deadlock prevention is
deadlock avoidance. With deadlock avoidance, a decision is made dynamically whether the
current resource allocation request will,if granted, potentially lead to a deadlock. Two
approaches to avoid deadlock .do not start a process if its demands might lead to deadlock.
Do not grant an incremental resource request to a process if this allocation might lead to
deadlock
By this algorithm A decision is made dynamically whether the current resource allocation
request will, if granted, potentially lead to a deadlock. This requires knowledge of future
process request.Do not start a process if its demands might lead to deadlock. Do not grant an
incremental resource request to a process if this allocation might lead to dead lock. The
following are to be considered

• Maximum resource requirement must be stated in advance


• Processes under consideration must be independent; no synchronization requirements
• There must be a fixed number of resources to allocate
• No process may exit while holding resources
33
34

Unsafe State.

Source code:
#include<stdio.h>
#include<conio.h>
int C[4][3],A[4][3],RQ[4][3],V[3],R[3],K[4],sum=0,np,nr;
main()
{
void fun();
int i,j,count=0,pcount=0;
clrscr();
printf("\nEnter the total number of resources : ");
scanf("\n%d",&nr);
for(i=0;i<nr;i++)
{
printf("\nEnter the no of resources int R%d : ",i+1);
35

scanf("%d",&R[i]);
}
printf("\nEnter the no of processes to be executed : ");
scanf("%d",&np);
printf("\nEnter the claim matrix:\n");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&C[i][j]);
printf("\nEnter the allocation matrix:\n");
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
scanf("%d",&A[i][j]);
for(i=0;i<np;i++)
for(j=0;j<nr;j++)
RQ[i][j] = C[i][j] - A[i][j]; /* FINDING THE REQUIRED
RESOURCES MATRIX(i.e., C-A) */
fun();
for(i=0;i<np;i++)
{
count=0;
f(K[i] == i+1)
continue; /* FOR SKIPPING THE PROCESSES(i.e., ROWS) WHICH
WERE ALREADY EXECUTED */
for(j=0;j<nr;j++)
{
if(V[j] >= RQ[i][j])
count++;
}
if(count == nr)
{
K[i] = i+1;
for(j=0;j<nr;j++)
C[i][j] = A[i][j] = RQ[i][j] = 0;
pcount++;
count = 0;
i=-1;
36

fun();
}
}

if(pcount == np)
printf("\nThere is no chance of deadlock.\nIt is a safe state.");
else
printf("\nThere is a chance of deadlock.\nIt isn't a safe state.");
getch();
}

void fun()
{
int i1,j1;
for(i1=0;i1<nr;i1++)
{
for(j1=0;j1<np;j1++)
{
sum = sum + A[j1][i1];
}
V[i1] = R[i1] - sum;
sum = 0;
}
}
37

Conclusion:
This algorithm verifies the presence of dead lock in the inputted system.
Sample i/p and o/p
Enter the total number of resources
2
Enter the total number of resources in R1
4
Enter the total number of resources in R2
5
Enter the total number of processes to be executed
4
Enter the claim matrix
2462
Enter the allocation matrix
1011
There is a chance of deadlock
It is not a safe state.
38

Practical – 5
Bankers Algorithm for Dead Lock Detection

Problem: Simulate Bankers Algorithm for Dead Lock Detection.

Aim: To simulate Bankers algorithm for Dead Lock Detection.

Problem description:

Dead Lock is defined as the permanent blocking of a set of processes that either compete for
system resources or communicate with each other. There is no efficient solution for this and
this Involves conflicting needs for resources by two or more processes.We can say the
existence of dead lock as

• Mutual Exclusion

• No preemption

• Hold and wait

• Circular Wait

This algorithm verifies of dead lock for the given system.

Explanation:
The Strategies once Deadlock Detected are abort all deadlocked processes,
Back up each deadlocked process to some previously defined checkpoint, and restart all process
(Original deadlock may occur),Successively abort deadlocked processes until deadlock no longer
exists ,Successively preempt resources until deadlock no longer exists

Source code:
#include<stdio.h>
#include<conio.h>
main()
{
int A[10][10],Q[10][10],W[10],R[10],V[10],B[10],mark[10];
int i,j,m,n,k,c=0;
clrscr();
printf("Enter row, column size\n");
scanf ("%d%d",&m,&n);
39

printf("Enter Allocation matrix\n");


for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&A[i][j]);

printf("Enter Request matrix\n");


for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&Q[i][j]);
printf("Enter Resource vector\n");
for(i=0;i<n;i++)
{
scanf("%d",&R[i]);
}
for(i=0;i<n;i++)
{
B[i]=0;

}
for(i=0;i<m;i++)
{
mark[i]=0;
}
for(i=0;i<n;i++)

{
for(j=0;j<m;j++)
{
B[i]=B[i]+A[j][i];
}
V[i]=R[i]-B[i];
}

for(k=0;k<n;k++)
W[k]=V[k];
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(A[i][j]==0)
c++;
if(c==n)
mark[i]=1;
}
c=0;
}
x: for(i=0;i<m;i++)
{
40

c=0;
for(j=0;j<n;j++)
{
if(Q[i][j]<=W[j] && mark[i]==0)
c++;
}

if(c==n)
{
mark[i]=1;
for(k=0;k<n;k++)
W[k]=W[k]+A[i][k];
goto x;

}
for(i=0;i<m;i++)
if(mark[i]==0)
printf("Process%d in deadlock state\n",i+1);
else
printf("process%d is not in deadlock\n",i+1);
getch();
}

Conclusion:
This algorithm verifies and detects the presence of dead lock and the processes that lead to
dead lock.
Sample input and output
Enter the number of processes
3
Enter the number of resources
3
Enter the request matrix
123456012

Enter the allocation matrix

789652301
Enter the resource vector
124
Process 1 leads to deadlock
Process 2 leads to deadlock
Process 3 leads to deadlock
41

Practical – 6
SEQUENTIAL FILE ALLCOATION
Problem: Simulate all file allocation strategies
a)Sequential b) Indexed c) Linked
Aim: To simulate sequential file allocation strategy algorithm
Problem description: The basic criteria for file organization are
• Short access time
– Needed when accessing a single record
– Not needed for batch mode
• Ease of update
– File on CD-ROM will not be updated, so this is not a concern
• Economy of storage
– Should be minimum redundancy in the data
– Redundancy can be used to speed access such as an index
• Simple maintenance
• Reliability
In the Sequential file organization a fixed format used for records.Records are the same
length.All fields the same (order and length).Field names and lengths are attributes of the
file.One field is the key filed.This field Uniquely identifies the record.Records are stored in
key sequence.New records are placed in a log file or transaction file.Batch update is
Performed to merge the log file with the master file
42

Explanation:

The contiguous allocation method requires each file to occupy a set of contiguous address on
the disk. Disk addresses define a linear ordering on the disk. Notice that, with this ordering,
accessing block b+1 after block b normally requires no head movement. When head
movement is needed (from the last sector of one cylinder to the first sector of the next
cylinder), it is only one track. Thus, the number of disk seeks required for accessing
contiguous allocated files in minimal, as is seek time when a seek is finally needed.
Contiguous allocation of a file is defined by the disk address and the length of the first block.
If the file is n blocks long, and starts at location b, then it occupies blocks b, b+1, b+2, …,
b+n-1. The directory entry for each file indicates the address of the starting block and the
length of the area allocated for this file.

The difficulty with contiguous allocation is finding space for a new file. If the file to be
created is n blocks long, then the OS must search for n free contiguous blocks. First-fit, best-
fit, and worst-fit strategies (as discussed in Chapter 4 on multiple partition allocation) are the
most common strategies used to select a free hole from the set of available holes. Simulations
have shown that both first-fit and best-fit are better than worst-fit in terms of both time
storage utilization. Neither first-fit nor best-fit is clearly best in terms of storage utilization,
but first-fit is generally faster.

These algorithms also suffer from external fragmentation. As files are allocated and deleted,
the free disk space is broken into little pieces. External fragmentation exists when enough
total disk space exists to satisfy a request, but this space not contiguous; storage is
fragmented into a large number of small holes.

Another problem with contiguous allocation is determining how much disk space is needed
for a file. When the file is created, the total amount of space it will need must be known and
allocated. How does the creator (program or person) know the size of the file to be created. In
some cases, this determination may be fairly simple (e.g. copying an existing file), but in
general the size of an output file may be difficult to estimate.

Source code
43

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct
{
int bno,flag;
}block;
block b[200];
void main()
{
int rnum();

int n,p[30],i,j,r,k[20][20],s,s1;
printf("\n input");

printf("\n enter no of files");


scanf("%d",&n);
printf("\n-------------------------------");
printf("\n enter memory requirements");
printf("\n------------------------------");
for(i=1;i<=n;i++)
{
printf("\n enter %d file requirements:",i);
scanf("%d",&p[i]);
}
for(i=1;i<=n;i++)
{
s1=rnum();
j=0;
for(s=s1;s<(s1+p[i]);s++)
{
j=j+1;
b[s].bno=s;
44

b[s].flag=1;
k[i][j]=s;
}
}
printf("\n output");
printf("\n ---------------------------------");
printf("\n program blocka allocated");
printf("\n----------------------------------");
for(i=1;i<=n;i++)
{
printf("%5d\t",i);
for(j=1;j<=p[i];j++)
printf("%5d",k[i][j]);
printf("'\n");
}
printf("\n------------------------------------");

printf("\n allocated blocks:");


printf("\n-----------------------------------");
for(i=1;i<=200;i++)
if(b[i].flag==1)
printf("%5d\t",b[i].bno);
}
int rnum()
{
int i,k=0;
for(i=1;i<=200;i++)
{
k=rand()%200;
if(k%2==0)
k=k+10;
if(b[k].flag!=1)
break;
return k;
}
45

Conclusion:
In the Sequential file organization a fixed format used for records.Records are the same
length.All fields the same (order and length).Field names and lengths are attributes of the
file.One field is the key filed.This field Uniquely identifies the record.Records are stored in
key sequence.New records are placed in a log file or transaction file.Batch update is
performed to merge the log file with the master file

Sample input and output


Enter the no of input files : 3
Input the requirements:
Enter the no of blocks needed in file 1: 2
Enter the no of blocks needed in file2 :4
Enter the no of blocks needed in file3: 3
Allocation
Allocate for file1: 8386
Allocate for file2: 77159335
Allocate for file3:924921
46

INDEXED FILE ALLOCATION

Problem: Simulate all file allocation strategies


a)Sequential b) Indexed c) Linked

Aim: To simulate Indexed file allocation strategy algorithm

Problem description:
The basic criteria for file organization are
• Short access time
– Needed when accessing a single record
– Not needed for batch mode
• Ease of update
– File on CD-ROM will not be updated, so this is not a concern
• Economy of storage
– Should be minimum redundancy in the data
– Redundancy can be used to speed access such as an index
• Simple maintenance
• Reliability

Index provides a lookup capability to quickly reach the vicinity of the desired record.This
Contains key field and a pointer to the main file.In Indexed is searched to find highest key
value that is equal to or precedes the desired key value.Here Search continues in the main file
at the location indicated by the pointer Indexed File Uses multiple indexes for different key
fields .This may contain an exhaustive index that contains one entry for every record in the
main file and this also may contain a partial index
47

Explanation:
The indexed allocation method is the solution to the problem of both contiguous and linked
allocation. This is done by bringing all the pointers together into one location called the index
block. Of course, the index block will occupy some space and thus could be considered as an
overhead of the method. In indexed allocation, each file has its own index block, which is an
array of disk sector of addresses. The ith entry in the index block points to the ith sector of
the file. The directory contains the address of the index block of a file. To read the ith sector
of the file, the pointer in the ith index block entry is read to find the desired sector. Indexed
allocation supports direct access, without suffering from external fragmentation. Any free
block anywhere on the disk may satisfy a request for more space.

Source code
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct block
{
int bno,flag;
};
struct block b[100];
int rnum();
48

void main()
{
int p[10],r[10][10],ab[10],i,j,n,s;
printf("\n INPUT");
printf("enter no of files:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\n enter the size of block %d:",i);
scanf("%d",&p[i]);
}
for(i=1;i<=n;i++)
{
s=rnum();
ab[i]=s;
for(j=0;j<p[i];j++)
{
s=rnum();
r[i][j]=s;
}
}
printf("\n output:");
for(i=1;i<=n;i++)
{
printf("\n file %d \n block %d contains:",i,ab[i]);
for(j=0;j<p[i];j++)
{
printf("%6d",r[i][j]);
}
}
}
int rnum()
{
int k=0,i;
for(i=1;i<=100;i++)
49

{
k=rand()%100;
if(b[k].flag!=-1)

break;
}
return k;
}

Conclusion:
This Contains key field and a pointer to the main file.In Indexed is searched to find highest
key value that is equal to or precedes the desired key value.Here Search continues in the main
file at the location indicated by the pointer
Sample output.
Enter the no of files: 3
---------------------------------------
Enter the memory requirements:
---------------------------------------
Enter the 1 file requirement: 3
Enter the 2 file requirement: 2
Enter the 3 file requirement: 4
-------------------------------------
Output
-------------------------------------
Program blocks allocated
-------------------------------------
1 70 71 72
2 115 116
3 212 213 214 215
-----------------------------------------
Allocated blocks
--------------------------------------------
70 71 72 115 116 212 213 214 215
50

LINKED FILE ALLCATION

Problem: Simulate all file allocation strategies


a)Sequential b) Indexed c) Linked

Aim: To simulate Linked file allocation strategy algorithm


Problem description:
The basic criteria for file organization are
• Short access time
– Needed when accessing a single record
– Not needed for batch mode
• Ease of update
– File on CD-ROM will not be updated, so this is not a concern
• Economy of storage
– Should be minimum redundancy in the data
– Redundancy can be used to speed access such as an index
• Simple maintenance
• Reliability

Explanation
The problems in contiguous allocation can be traced directly to the requirement that the
spaces be allocated contiguously and that the files that need these spaces are of different
sizes. These requirements can be avoided by using linked allocation.

In linked allocation, each file is a linked list of disk blocks. The directory contains a pointer
to the first and (optionally the last) block of the file. For example, a file of 5 blocks which
starts at block 4, might continue at block 7, then block 16, block 10, and finally block 27.
Each block contains a pointer to the next block and the last block contains a NIL pointer. The
value -1 may be used for NIL to differentiate it from block 0.

With linked allocation, each directory entry has a pointer to the first disk block of the file.
This pointer is initialized to nil (the end-of-list pointer value) to signify an empty file. A write
to a file removes the first free block and writes to that block. This new block is then linked to
the end of the file. To read a file, the pointers are just followed from block to block.
51

There is no external fragmentation with linked allocation. Any free block can be used to
satisfy a request. Notice also that there is no need to declare the size of a file when that file is
created. A file can continue to grow as long as there are free blocks. Linked allocation, does
have disadvantages, however. The major problem is that it is inefficient to support direct-
access; it is effective only for sequential-access files. To find the ith block of a file, it must
start at the beginning of that file and follow the pointers until the ith block is reached. Note
that each access to a pointer requires a disk read.

Source code
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct
{
int bno,flag,bn[20];
}block;
block b[100],b1;
void main()
{
int rnum();
int p[30],kk[20],i,n,t,s1,s,r,j,c=1;
printf("\n enter no of i/p files");
scanf("%d",&n);
printf("\n input the requirements");
for(i=1;i<=n;i++)
{
printf("\n enter the no of blocks needed for file%d",i);
scanf("%d",&p[i]);
}
t=1;
for(i=1;i<=n;i++)
{
for(j=1;j<=p[i];j++)
{
s=rnum();
b[s].flag=1;
52

b[c].bno=s;
r=p[i]-1;
kk[i]=s;
t=1;
c++;
}
}
while(r!=0)
{
s1=rnum();
b[s].bn[t]=s1;
b[s1].flag=1;
b[c].bno=s1;

r=r-1;
t=t+1;
c++;
}
printf("\n allocation:\n");

c=1;
for(i=1;i<=n;i++)
{
printf("\n allocated for file%d",i);
for(j=1;j<=p[i];j++)
{
if(j==1)
{
printf("%3d",b[c].bno);
c++;
}
53

else
{
printf("---->%3d",b[c].bno);
c++;
}
}
printf("\n");
}
}
int rnum()
{
int k=0,i;
for(i=1;i<=100;i++)
{
k=rand()%100;
if(b[k].flag!=1)
break;
}
return k;
}

Conclusion:
There is no external fragmentation with linked allocation. Any free block can be used to
satisfy a request. Notice also that there is no need to declare the size of a file when that file is
created.

Sample input and output.


Enter the no of files 3
Enter the size of block 1 2 3
4 3 2
File 1 Block 83 contains 86 77 15 93
File 2 Block 85 contains 86 92 49
File 3 Block 21 contains 62 27
54

Practical – 7
FILE ORGANIZATION TECHNIQUES
Aim : Program to simulate “two level directory” method of file organization.

Theory: The major disadvantage to a single-level directory is the confusion of file names
between different users. The solution is to create a separate directory for each user.In a two-
level directory structure, each user has his own file directory. Each file directory has a similar
structure, but lists only the files of a single user. When a user job starts or a user logs in, the
system’s master file directory is searched and then user’s directory is searched.When a user
refers to a particular file, only his own directory is searched. Thus different users may have
files with the same name, but files within same directory should have unique names.

Master directory User 1 User 2 User 3

User directory
sat cat mat mat pat rat pat sat

Two – level directory structure

Algorithm
1. Start
2. Enter number of users: n
3. //master directory information create a master directory and enter name of each user
directory
4. //user directory information for each user directory enter number of files and their
names and file information.
5. To enter a new file : get a particular user directory and enter the file at the last of that
directory.
6. To read/write a file : get directory name and file name and read that file, or write into
it. i.e., master directory  user directory  file name
7. To delete a file: select the path of that file and free the file node.
8. To delete a directory ; selected the path of the directory and free the reference pointer
to it.
9. To delete master directory: all user directory should be deleted first
10. end
55

Aim : To simulate hierarchical file organization techniques

Theory: Hierarchical organization is the extended directory structure of 2-level directory


organization. Here a directory contains number of unique files and may contain a
subdirectory. Each subdirectory may contain further subdirectory and files. In normal use,
each user has a current directory. The current directory should contain most of the files that
are of current interest to the user. When reference is made to a file, the current directory is
searched. If a file is needed that is not in the current directory, then the user must either
specify a path name or change the current directory to be the directory holding that file.

ROOT : A B C

cat M N rat mat rat pat

sra srm srp dog dig

A, B, C  root directory; M, N  sub directory

cat, rat, mat, pat, sra, srm, srp, dog, dag  files

Algorithm
1. Enter number of users and enter the name of each user directory into root directory.
2. Enter filenames and sub directories into each user directory
3. If it is a subdirectory then enter the files under this directory.
4. To read a file: specify a path from root directory via any sub directory up to that file
and read the file.
5. To write into a file : specify the path as above and write into that file.
6. To delete a directory: if directory is empty delete it, else delete all subdirectory and
files under it, then delete the desired directory.
56

Input:
Enter number of users : 2
Name of user directory 1 : A
Name of user directory 2 : B
Name of files under A : cat
Name of sub directory under A : M
Name of files under M : sra, srm, srp
Namd of files under B : rat
Name of subdirectory under B : N
Name of files under N : dog, dig

Output:

A  cat/m
M  sra/srm/srp
B  rat/N
N  dog/dig
57

Aim : To simulate DAG file organization technique

Theory: A tree structure prohibits the sharing of files or directories. An acidic graph allows
directories to have shared subdirectories and files. The same file or sub directory may be in
two different directories.

In a situation where several people are working as a team, all the files to be shared may be
put together into one directory. The user file directories of all the team members would each
contain this directory or shared files as a subdirectory. Even when there is a single user, his
file organization may require that some files be put into several different subdirectories.

`
ROOT: A B C

cat mat M M sat N

Fat rat dig

Here, subdirectory M of user A and B, are sharing a file fat.

Algorithm:
1. Enter number of users :n
2. Create a root directory and a shared directory
3. Enter the files of each directory and shared directory
4. Make shared directory as a subdirectory of each directory.
5. To read a file : specify the path name and read the file
6. To write into a file : specify the path and write into it.
7. To delete a directory: delete all the files ad subdirectories first and then only you are
allowed to delete a directory.
58

Practical – 8

PAGING TECHNIQUE

Aim : Program to implementing the paging technique for memory management

Theory: Paging gives a solution to the external fragmentation. Here physical memory is
broken into fined sized blocks called frames. Logical memory is broken down into same size
blocks called pages. When a process is to be executed it’s pages are loaded into any available
frames from backing store.
Let’s consider we are having two processes: P0 and P1. P0 is of 3 bytes size and P1 is of 8
byte size. Total main memory size is 20 byte. Now main memory is divided into fixed sized
frames. Suppose each page requires 4 bytes, then we have number of frames = 20byte/4byte
=5

0 1 2 3 4
Page - 0 a 0 0 1 a
Fn[0] 0
1 1 2 b
b
e c 1
Page - 1
c Page table Fn[1] e
f
h f
Page - 2 2
g g
i
Page - 3
Page - 4 j Fn[2] i h 3
j
Logical Memory
k 4

Fn[3] free l
Fn[4] free
Main Memory

Now Process P0 requires 1 page and process P1 requires 2 pages since their sizes are 3 byte
and 8 byte respectively.
Let data of process P0 = abc
Let data of process P1 = efghijkl
Now information in page-0 = abc
Information in page-1 = efgh
Information in page-2 = ijkl
59

Let index of process P0 = 0


Index of process P1 = 1
Index of process P2 = 2
Enter these index numbers into array of page table. Rows of a page table indicates number of
processes and column of a page table indicates frame numbers of main memory.
Now enter the information of each page into frames of main memory according to page table
i.e., page-0 will be stored in frame-0
Page-1 will be stored in frame-1
Page-2 will be stored in frame-2
And rest frames will be indicated as free.
Now if user will give the process index number and logical address of the process i.e., index,
pageno, offset then we can get the particular data by mapping logical address into physical
address of memory.
Let index = 1, pageno = 1, offset = 2
Then frame number = page table[index][pageno]
= page table[1][1] = 2
Physical address = [frame number, offset]
= fon[2,2]
= frame number * page size + offset
= 2 x 4 + 2 = 10
Information at address 10 of main memory = k

Algorithm

1. Begin
2. Enter number of processes: n
enter memory size : ms
enter page size : ps
// calculate number of frames.
3. If ms mod ps = = 0 then
number of frames : tm := ms/ps
else tm := ms/ps + 1
4. //Calculate how many pases each process requires and enter information & each
page.
For i := 0 to n in steps of 1
Begin
60

Enter size of process p(i)


Calculate total number of pages for p(i) : +p(i)
For j :=0 to +p(i) in steps of 1
Begin
Enter information on each page : pinfo(i.j)
End for
End for
5. //entry into page table
for i := 0 to n
begin
for j := 0 to tp(i)
begin
enter page no: ptable(i, j)
fm(ptable(i,j)) := used
fm(ptable(i,j)).index := i
fm(ptable(i,j).info) := pinfo(i, j)
end for
end for
6. //current main memory allocation
for i := 0 to tm
begin
if tm(i) := used then
print : (i, fm(i).info)
else
print(frame i is free)
end for
7. //process the query of user
enter process index: pin
enter logical addres: pageno, offset
fno := ptable(pin, page no)
//physical address
location := fno * ps + offset
value := fm(fno.info(offset))
print: location, value
8 end
61

Input:
number of process n = 2

Output:
Memory size ms = 20
Page size ps = 4
Tm = 5
Size of process p(0) = 3
Size of process p(1) = 8
Total no. of pages for p(0) = 1 and p(1) = 2
Enter information on each page :
Pinfo(0,0) = a, b, c
Pinfo(1,0) = e, f, g, h
Pinfo(1,1) = i, j, k, l

Main memory allocation:


0, a, b, c
1, e, f, g, h
2, i, j, k, l
3, free
4, free
5, free

enter process index: pin = 1


enter logical address : page no, offset: 1, 2
physical addres:
location: 10
Value : k
62

ADDON-1

Aim : First fit storage placement

Theory: Storage placement strategies are used to determine where in main storage to place
incoming programs and data.

First fit strategy suggest that an incoming job is placed in the main storage in the first
available hole large enough to hold it. i.e. place job in first storage hole if it will fit.

Example:

O/S
Request for First fit hole
16K
10k
USE hole

14K
hole
USE

28K

Algorithm Explanation:
Assign the holes of various sizes to an array. First hole to first element of array and so on.
Here a[0]=16k, a[1]=14k, a[2]=28k. get the size of requested job. Compare this job size to all
array elements from a[0]…..a[2]. Up to when the size of requested job is less then or equal to
array element. Then allocate the job to this hole. And give an indication that this hole has
been allocated.

Repeat this process for other requested jobs also.

First Fit Algorithm:

1. Begin

Enter number of holes : n

2. For i:=0 to n-1 in steps of 1

Begin

Flag(i) :=0

Enter size of each hole:a(i)


63

End for

3. max := a(0)

4. for i :=0 to n-1 in steps of 1

Begin

If (a(i) > max) then

Max := a(1)

End for

5. print : max

6. For i := 0 to n-1 in steps of 1

Begin

Enter the job size to be placed in hole

If(size > max) then

Print : job is not fit for any hole

i := i-1

else

for k :=0 to n-1 in steps 1

Begin

If (size <= a(k) and flag(k) := 0)

Print: job can be placed in the hole with memory wastage of a(k) – size MB

Flag(k) = 1

End if

End for

End for

8. End

In put:
Enter number of holes : n 4
64

Out put:

Enter size of each hole:

a(0) 20

a(1) 15
a(2) 30
a(3) 25
Enter the job size to be placed in the hole : 15 job can be placed in the hole with
memory wastage of 5 mb Enter the job size to be placed in the hole: 20 job can be
placed in the hole with memory wastage of 10 mb
65

ADDON-2

Aim : Best Fit Storage Placement

Theory: Best fit storage placement strategy suggests that an incoming job is placed in the
hole in main storage in which it fit’s must tightly and leaves the smallest amount of unused
space, i.e., place a job in smallest possible hole in which it will fit well. This is the most
reliable method for hole allocation amongst all other available strategies.

Example:

O/S O/S
16K 16K
USE After USE Best fit Request for
14K sorting 14K 10K

USE USE
28K 28K

First of all the holes available will be allocated to an array a[ ]. Then array a[ ] will be sorted
in ascending order of hole size. The requested job size will be allocated to that hole, which
will be fit well to it. It compares job size with each hole size from a[0]…..a[n], when ever the
size will be less than or equal to array hole size it will be allocated, and that hole will be
indicated as allocated.

Now if any other requested job will come then again the above process will be repeated.

Here before sorting: a(0) – 16, a(1) – 14, a(2) – 28

After sorting : a(0) – 14, a(1) – 16, a(2) – 28

Since requested job size 10k < 14k of a(0), hence 14k will be allocated to the requested job of
10k leaving 4k unused memory.
66

Best Fit Algorithm


1. Begin
Enter total number of holes present
2. for i = 0 to n-1 in steps of 1
begin
enter size of each hole: a(i)

flag(i) := 0
end for
3. for i = 0 to n-1 in steps of 1
find maximum hole size : max end for
print : max
4. for i := 0 to n-2 in steps of 1
for j := i+1 to n-1 in steps of 1
begin
if(a(i) > a(j)) then
exchange(a(i), a(j))
end for
5. for i := 0 to n-1 in steps of 1
begin

enter job size : size

if(size > max) then

print: not fit for any hole

i := i-1

end if

6. Else

for k := 0 to n-1 in steps of 1

begin

if(size < = a(k) and flag(k)=0) then

print: job can be placed with a(k) size mb of wastage memory


67

end if

end for

end for

7. end

Input / Output
Enter total no. of holes present n: 4

Enter size of each hole: 20 15 30 25

Max hole size is 30 mb

Enter job size to be placed in a hole: 15

Job can be placed with 0 mb of whastage memory

Enter job size to be placed in a hole : 22

Job can be placed with 8 mb wastage memory

Enter job size to be placed in hole 28

Job can be placed with 2mb wastage memory

Enter job size to be placed in a hole: 18

Job can be placed with 2mb wastage memory.


68

ADDON-3

Aim : Worst Fit Storage Placement

Theory: Worst fir is an in efficient algorithm for storage placement strategies. It status that ,
an incoming job is placed in the largest hole in which it will fit well.Here the holes are sorted
in descending order of hole size. The requested job will be given the first hole if it can fit for
the job size. Hence of a small size job is these and a large hole to accommodate, then a lot of
memory wastage will occur. Hence it is the last choice of storage placement.

Example:

O/S O/S

16K hole 28K hole


After Best fit Request for
USE sorting USE 10K

14K hole 16K hole


USE USE

28K hole 14K


hole

Initially assign the holes to an array a[ ]. Sort the array in descending order of hole size. Then
allocate the requested job size to the first hole if it will fit else go for next hole and so on. If a
hole will fit then mark it as allocated and if any further request will come then repeat the
same process as above

Worst Fit Algorithm


1. Begin:
enter number of holes: n
2. for i := 0 to n-1 in steps of 1
enter size of each hole : a(i)
flag(i) := 0
end for
69

3. find maximum hole size max among


each a(i)
print : max

4. for i:=0 to n-1 in steps of 1


for j :=0 to n-2-i in steps of 1
if(a(j+1) > a(j)) then
exchange : a(j+1), a(j) //get arge hole at a(0) position
end if
end for
5. for i :=0 to n-1 insteps of 1
begin
enter job size you want to place : size
if (size > max) then
print cannot fit into any hole
i := i-1
end if
6. Else
for k : =0 to n-1 in steps of 1
begin
If (size < = a(k) and flag(k) = 0
Print: job can be placed in a(k) – size mb of memory wastage
Flag(k) := 1
End if
End for
End for
7. End
70

Input / Output:
Enter number of holes n : 4
Enter size of each hole : 20 15 30 25
Max size of hole : 30
Enter job size you want to place : 20
Job can be placed in 10 mb of memory wastage
Enter job size you want to place : 20
Job can be placed in 5 mb of memory wastage
Enter job size you want to place: 15
Job can be placed in 5 mb of memory wastage
Enter job size you want to place: 15
Job can be placed in 0 mb of memory wastage

You might also like