(CN & Os) Final Lab Manual
(CN & Os) Final Lab Manual
Practical – 1
ROUND ROBIN
Problem description:
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
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
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:
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.
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 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);
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.
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 200, 230. 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
231 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., 531.
This process is repeated until the reference string pages are placed onto the frames, then
finally 352 are the process pages in the frame.
Solution steps:
}
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
<5> 5 2 4
<3> 3 2 4
<2> 3 2 4
<5> 3 5 4
<2> 3 5 2
Page Faults:6
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
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 231.Like that least
recently used value will be placed with new value and for every replacement page fault is counted.
Solution steps:
Source code:
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.
Page Faults:4
24
Practical – 3
MVT
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:
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.
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 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:
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
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 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
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
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 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
• Circular Wait
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
}
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
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");
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------------------------------------");
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
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
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.
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.
User directory
sat cat mat mat pat rat pat sat
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
ROOT : A B C
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
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
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
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
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
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
ADDON-1
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.
1. Begin
Begin
Flag(i) :=0
End for
3. max := a(0)
Begin
Max := a(1)
End for
5. print : max
Begin
i := i-1
else
Begin
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:
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
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.
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
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
i := i-1
end if
6. Else
begin
end if
end for
end for
7. end
Input / Output
Enter total no. of holes present n: 4
ADDON-3
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
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
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