You are on page 1of 96

Exp.

No: 1(a) ROUND ROBIN SCHEDULING

AIM: Write a C program to implement the various process scheduling


mechanisms such as Round Robin Scheduling.

THEORY:
Scheduling is a fundamental operating system function. CPU
scheduling is the basis of multi programming operating system. CPU
scheduling algorithm determines how the CPU will be allocated to the
process. These are of two types.

1. Primitive scheduling algorithms


2. Non-Primitive scheduling algorithms

1) Primitive Scheduling algorithms: In this, the CPU can release the


process even in the middle of execution. For example: the CPU executes
the process p1, in the middle of execution the CPU received a request
signal from process p2, then the OS compares the priorities of p1&p2. If
the priority p1 is higher than the p2 then the CPU continue the execution
of process p1. Otherwise the CPU preempts the process p1 and assigned
to process p2.
2) Non-Primitive Scheduling algorithm: In this, once the CPU assigned
to a process the processor do not release until the completion of that
process. The CPU will assign to some other job only after the previous
job has finished.

Scheduling methodology:
Though put: It means how many jobs are completed by the CPU with in
a time period.
Turnaround time: The time interval between the submission of the
process and the time of the completion is the turnaround time.
Turnaround time=Finished time – arrival time
Waiting time: it is the sum of the periods spent waiting by a process in
the ready queue
Waiting time=Starting time- arrival time
Response time: it is the time duration between the submission and first
response
Response time=First response-arrival time
CPU Utilization: This is the percentage of time that the processor is
busy. CPU utilization may range from 0 to 100%

First-come, first-serve scheduling (FCFS): In this, which process enter


the ready queue first is served first. The OS maintains DS that is ready
queue. It is the simplest CPU scheduling algorithm. If a process requests
the CPU then it is loaded into the ready queue, which process is the
head of the ready queue, connect the CPU to that process.
Shortest job First: The criteria of this algorithm are which process
having the smallest CPU burst, CPU is assigned to that next process. If
two process having the same CPU burst time FCFS is used to break the
tie.

Priority Scheduling: These are of two types.

One is internal priority, second is external priority. The CPU is


allocated to the process with the highest priority. Equal priority
processes are scheduled in the FCFS order. Priorities are generally
some fixed range of numbers such as 0 to 409. The low numbers
represent high priority.
Round Robin: It is a primitive scheduling algorithm it is designed
especially for time sharing systems. In this, the CPU switches between
the processes. When the time quantum expired, the CPU switches to
another job. A small unit of time called a quantum or time slice. A time
quantum is generally is a Circular queue new processes are added to the
tail of the ready queue.

If the process may have a CPU burst of less than one time slice
then the process release the CPU voluntarily. The scheduler will then
process to next process ready queue otherwise; the process will be put at
the tail of the ready queue.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue and time
quantum (or) time slice
Step 3: For each process in the ready Q, assign the process id and
accept the CPU burst time
Step 4: Calculate the no. of time slices for each process where
No. of time slice for process(n) = burst time process(n)/time slice
Step 5: If the burst time is less than the time slice then the no. of time
slices =1.
Step 6: Consider the ready queue is a circular Q, calculate
a. Waiting time for process(n) = waiting time of process(n-1)+
burst time of process(n-1 ) + the time difference in getting the
CPU from process(n-1)
b. Turnaround time for process(n) = waiting time of process(n) +
burst time of process(n)+ the time difference in getting CPU
from process(n).
Step 7: Calculate
a. Average waiting time = Total waiting Time / Number of process
b. Average Turnaround time = Total Turnaround Time / Number
of process
Step 8: Stop the process

PROGRAM:
/* ROUND ROBIN SCHEDULING ALGORITHM */
#include<stdio.h>
#include<conio.h>
void main()
{
int ts,pid[10],need[10],wt[10],tat[10],i,j,n,n1;
int bt[10],flag[10],ttat=0,twt=0;
float awt,atat;
clrscr();

printf("\t\t ROUND ROBIN SCHEDULING \n");


printf("Enter the number of Processors \n");
scanf("%d",&n);

n1=n;
printf("\n Enter the Timeslice \n");
scanf("%d",&ts);
for(i=1;i<=n;i++)
{
printf("\n Enter the process ID %d",i);
scanf("%d",&pid[i]);
printf("\n Enter the Burst Time for the process");
scanf("%d",&bt[i]);
need[i]=bt[i];
}
for(i=1;i<=n;i++)
{
flag[i]=1;
wt[i]=0;
}
while(n!=0)
{
for(i=1;i<=n;i++)
{
if(need[i]>=ts)
{
for(j=1;j<=n;j++)
{
if((i!=j)&&(flag[i]==1)&&(need[j]!=0))
wt[j]+=ts;
}
need[i]-=ts;
if(need[i]==0)
{
flag[i]=0;
n--;
}
}
else
{
for(j=1;j<=n;j++)
{
if((i!=j)&&(flag[i]==1)&&(need[j]!=0))
wt[j]+=need[i];
}
need[i]=0;
n--;
flag[i]=0;
}
}
}
for(i=1;i<=n1;i++)
{
tat[i]=wt[i]+bt[i];
twt=twt+wt[i];
ttat=ttat+tat[i];
}
awt=(float)twt/n1;
atat=(float)ttat/n1;
printf("\n\n ROUND ROBIN SCHEDULING ALGORITHM \n\n");
printf("\n\n Process \t Process ID \t BurstTime \t Waiting Time \t
TurnaroundTime \n ");
for(i=1;i<=n1;i++)
{
printf("\n %5d \t %5d \t\t %5d \t\t %5d \t\t %5d \n",
i,pid[i],bt[i],wt[i],tat[i]);
}

printf("\n The average Waiting Time=%f",awt);


printf("\n The average Turnaround Time=%f",atat);
getch();
}
APPLICATIONS:

• When two systems are exchanging the packets in simplex mode,


then the users has to wait till the completion transmission by one
user. in this case, network administrators will fix some time slice
for exchange of information.

• Token management in session layer of ISO/OSI reference model


allows the users to create sessions to transmit the data among the
networks.

• IEEE 802.5 Token ring allows the access control mechanism to


exchange the data based on passing of tokens among users, by
placing time slices at every user for token by 200 micro seconds
each.

• The Online Chat System (or) Online mail system allows selecting
arbitrarily which users will receive the message during
communication between many users connected to system. The
system also may define an algorithm for selecting which user will
receive the message.
INFERENCE: The student understands the execution of multiple
processes simultaneously by the CPU with a time quantum.

QUESTIONS:
• What is Preemptive algorithm? Explain?
• Who proposed this round robin algorithm?
• List the drawbacks of round robin algorithm?
• Give the alternate name for round robin algorithm?
• Differentiate in between round robin and SJF?
• What schedulers are used to achieve round robin?
• List the dichotomies in between long-term and short-term
scheduler?
• Compare and contrast in between process and scheduling?

Exp. No: 1(b) SJF SCHEDULING

AIM: Write a C program to implement the various process scheduling


mechanisms such as SJF Scheduling.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and
accept the CPU burst time
Step 4: Start the Ready Q according the shortest Burst time by sorting
according to lowest to highest burst time.
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround
time as its burst time.
Step 6: For each process in the ready queue, calculate
a. Waiting time for process(n)= waiting time of process (n-1) +
Burst time of process(n-1)
b. Turnaround time for Process(n)= waiting time of Process(n)+
Burst time for process(n)
Step 6: Calculate
a. Average waiting time = Total waiting Time / Number of process
b. Average Turnaround time = Total Turnaround Time / Number
of process
Step 7: Stop the process

PROGRAM:

/* SJF SCHEDULING ALGORITHM */

#include<stdio.h>
void main()
{
int i,j,k,n,sum,wt[10],tt[10],twt,ttat;
int t[10],p[10];
float awt,atat;
clrscr();

printf("Enter number of process\n");


scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("\n Enter the Burst Time of Process %d",i);
scanf("\n %d",&t[i]);
}

for(i=0;i<n;i++)
p[i]=i;
for(i=0;i<n;i++)
{
for(k=i+1;k<n;k++)
{
if(t[i]>t[k])
{
int temp;
temp=t[i];
t[i]=t[k];
t[k]=temp;

temp=p[i];
p[i]=p[k];
p[k]=temp;
}
}
printf("\n\n SHORTEST JOB FIRST SCHEDULING ALGORITHM");
printf("\n PROCESS ID \t BURST TIME \t WAITING TIME \t
TURNAROUND TIME \n\n");
wt[0]=0;
for(i=0;i<n;i++)
{
sum=0;
for(k=0;k<i;k++)
{
wt[i]=sum+t[k];
sum=wt[i];
}
}
for(i=0;i<n;i++)
{
tt[i]=t[i]+wt[i];
}
for(i=0;i<n;i++)
{
printf("%5d \t\t5%d \t\t %5d \t\t %5d \n\n",p[i],t[i],wt[i],tt[i]);
}
twt=0;
ttat=t[0];
for(i=1;i<n;i++)
{
twt=twt+wt[i];
ttat=ttat+tt[i];
}
awt=(float)twt/n;
atat=(float)ttat/n;

printf("\n AVERAGE WAITING TIME %4.2f",awt);


printf("\n AVERAGE TURN AROUND TIME %4.2f",atat);
getch();
}
}
APPLICATIONS:

• Some organizations will issue the salaries for the employees, who
are having the low amount of salary. Later the high amount
salaries will be issued to the employees, who are having high
salary.
• When huge number of customers, visit a general store, the
customer who purchases less number of products will undergo
billing process and shopping faster than customers, who purchases
many products.

• The passengers, who travel in the train for short distance will
reach destination early than the passengers, who travel for longer
distance.

• When many customers place order in hotel, customer with few set
of ordered list will be served first than the customer with plenty set
of order.
INFERENCE: The student understands that using the SJF CPU
Scheduling algorithm,
the process whose burst time is minimum of the processes in the
ready queue
will be executed first by the CPU.

QUESTIONS:

• What is preemption?
• What is SRTF?
• Does preemption halt system generated processes?
• What is exponential average?
• What is the cause for preempting a process?
• Does the cost of preemption affect interrupts?
• What is burst time of process?
• Why SJF scheduling algorithm is is optimal?
Exp. No: 1(c) FCFS SCHEDULING
AIM: Write a C program to implement the various process scheduling
mechanisms such as FCFS scheduling.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and
accept the CPU burst time
Step 4: Set the waiting of the first process as ‘0’ and its burst time as its
turn around time
Step 5: for each process in the Ready Q calculate
a. Waiting time for process(n)= waiting time of process (n-1) +
Burst time of process(n-1)
b. Turnaround time for Process(n)= waiting time of Process(n)+
Burst time for process(n)
Step 6: Calculate
a. Average waiting time = Total waiting Time / Number of process
b. Average Turnaround time = Total Turnaround Time / Number
of process
Step 7: Stop the process

PROGRAM:

/* FCFS SCHEDULING ALGORITHM */

#include<stdio.h>
void main()
{
int i,n,sum,wt,tat,twt,ttat;
int t[10];
float awt,atat;
clrscr();
printf("Enter number of processors:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter the Burst Time of the process %d",i+1);
scanf("\n %d",&t[i]);
}

printf("\n\n FIRST COME FIRST SERVE SCHEDULING ALGORITHM


\n");
printf("\n Process ID \t Waiting Time \t Turn Around Time \n");
printf("1 \t\t 0 \t\t %d \n",t[0]);
sum=0;
twt=0;
ttat=t[0];

for(i=1;i<n;i++)
{
sum+=t[i-1];
wt=sum;
tat=sum+t[i];
twt=twt+wt;
ttat=ttat+tat;
printf("\n %d \t\t %d \t\t %d",i+1,wt,tat);
printf("\n\n");
}

awt=(float)twt/n;
atat=(float)ttat/n;
printf("\n Average Waiting Time %4.2f",awt);
printf("\n Average Turnaround Time %4.2f",atat);
getch();
}

APPLICATIONS:

• The passengers at airport gateway, who enters at first, will be


allowed to go to the plane at first than the passengers, who comes
late.
• The people who enter into a ticket counter of a theatre at first,
served by the ticket than the people, who are behind.

• The person, who books a vehicle in advance or at first, will receive


it first than others who book later.
• Passenger who books ticket first through online reservation system
will get ticket reserved basing on availability.

INFERENCE: The student understands that using the FCFS CPU


Scheduling algorithm,
the process which is entered into the ready queue will be executed
first by the CPU

QUESTIONS:
• What is non-preemption? Give examples?
• What are limitations of FCFS scheduling?
• What happens if two processes enter queue at once?
• What are the differences between FCFS and SJF scheduling
algorithms?
• List the critiques on FCFS scheduling algorithm?
• What is turnaround time? How to calculate ATT?
• What is response time? Explain?
• Compare and contrast in between FCFS and Round robin
scheduling algorithm?

Exp. No: 1(d) PRIORITY SCHEDULING

AIM: Write a C program to implement the various process scheduling


mechanisms such as Priority Scheduling.
ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and
accept the CPU burst time
Step 4: Sort the ready queue according to the priority number.
Step 5: Set the waiting of the first process as ‘0’ and its burst time as its
turn around time
Step 6: For each process in the Ready Q calculate
a. Waiting time for process(n)= waiting time of process (n-1) +
Burst time of process(n-1)
b. Turnaround time for Process(n)= waiting time of Process(n)+
Burst time for process(n)
Step 7: Calculate
a. Average waiting time = Total waiting Time / Number of process
b. Average Turnaround time = Total Turnaround Time / Number
of process
Step 8: Stop the process

PROGRAM:

/* PRIORITY SCHEDULING */

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

void main()
{
int i,j,n,tat[10],wt[10],bt[10],pid[10],pr[10],t,twt=0,ttat=0;
float awt,atat;
clrscr();
printf("\n-----------PRIORITY SCHEDULING--------------\n");
printf("Enter the No of Process: ");
scanf("%d", &n);
for (i=0;i<n;i++)
{
pid[i] = i;
printf("Enter the Burst time of Pid %d : ",i);
scanf("%d",&bt[i]);
printf("Enter the Priority of Pid %d : ",i);
scanf ("%d",&pr[i]);
}

// Sorting start
for (i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if (pr[i] > pr[j] )
{
t = pr[i];
pr[i] = pr[j];
pr[j] = t;

t = bt[i];
bt[i] = bt[j];
bt[j] = t;

t = pid[i];
pid[i] = pid[j];
pid[j] = t;
}
}
// Sorting finished

tat[0] = bt[0];
wt[0] = 0;

for (i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = wt[i] + bt[i];
}

printf("\n---------------------------------------------------------------\n");
printf("Pid\t Priority\tBurst time\t
WaitingTime\tTurnArroundTime\n");
printf("\n--------------------------------------------------------------\n");

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

printf("\n%d\t\t%d\t%d\t\t%d\t\t%d",pid[i],pr[i],bt[i],wt[i],tat[i]);
}

for(i=0;i<n;i++)
{
ttat = ttat+tat[i];
twt = twt + wt[i];
}

awt = (float)twt / n;
atat = (float)ttat / n;
printf("\n\nAvg.Waiting Time: %f\nAvg.Turn Around Time:
%f\n",awt,atat);
getch();
}

APPLICATIONS:
• Each traffic light in our simulation would have an event
scheduled for its next change. When a light changes to red, we
schedule it's next change to green some number of seconds later.
When a light changes to green, we schedule a change-to-yellow
event some time a little later, and so on.
• Parking lots and garages might be simulated as objects that, at
random time intervals, toss a new car out on to the street in front
of the lot or garage. The average size of the car-generation
interval would vary with the time of day.
• Each moving car on the street would have an event associated
with the time it needs to reach the next intersection along its
path. When it reaches that intersection, we schedule a new event
for the intersection after that, and so on.
INFERENCE: The student understands that using the PJF CPU
Scheduling algorithm,
the process which are waiting for the CPU in the ready
queue are executed as per their priority.

QUESTIONS:

• What is Scheduling? Why it is used?


• What is Priority? How it is useful in Scheduling?
• What is Starvation?
• What is Aging?
• Compare Priority scheduling and SJF?
• What happens when two processes have same priority?
• What is the prominence of Priority scheduling?
• Develop a Gantt chart for following process
Process Priority
P1 10
P2 3
P3 7

Exp. No: 3(a) Single Level Directory

AIM: Simulate file organization techniques for Single Level Directory.

THEORY:
The directory contains information about the files, including attributes,
location and ownership, and sometimes the directories consisting of
subdirectories also. The directory is itself a file, owned by the operating
system and accessible by various file management routines.
a) Single Level Directories: It is the simplest of all directory structures,
in this the directory system having only one directory, it consisting of the
all files. Sometimes it is said to be root directory. The following dig.
Shows single level directory that contains four files (A, B, C, D).

It has the simplicity and ability to locate files quickly. it is not used
in the multi-user system, it is used on small embedded system.

b) Two Level Directory: The problem in single level directory is


different users may be accidentally using the same names for their files.
To avoid this problem, each user need a private directory. In this way
names chosen by one user don’t interface with names chosen by a
different user. The following dig 2-level directory
Here root directory is the first level directory it consisting of
entries of user directory. User1, User2, User3 are the user levels of
directories. A, B, C are the files

c) Hierarchical Directory: The two level directories eliminate name


conflicts among users but it is not satisfactory for users but it is not
satisfactory for users with a large no of files. To avoid this, create the
subdirectory and load the same type of the files into the subdirectory.
So, in this method each can have as many directories are needed.
This directory structure looks like tree, that’s why it is also said to
be tree-level directory structure

Exp. No: 3(a)

AIM: Simulate file organization techniques for Single Level Directory.

#include<stdio.h>
#include<conio.h>
main()
{
int master,s[20];
char f[20][20][20];
char d[20][20];
int i,j;
clrscr();
printf("enter number of directorios:");
scanf("%d",&master);
printf("enter names of directories:");
for(i=0;i<master;i++)
scanf("%s",&d[i]);
printf("enter size of directories:");
for(i=0;i<master;i++)
scanf("%d",&s[i]);
printf("enter the file names :");
for(i=0;i<master;i++)
for(j=0;j<s[i];j++)
scanf("%s",&f[i][j]);
printf("\n");
printf(" directory\tsize\tfilenames\n");
printf("*************************************************\n")
;
for(i=0;i<master;i++)
{
printf("%s\t\t%2d\t",d[i],s[i]);
for(j=0;j<s[i];j++)
printf("%s\n\t\t\t",f[i][j]);
printf("\n");
}
printf("\t\n");
getch();
}

Exp. No: 3(b) Two Level Directories

AIM: Simulate file organization techniques for Two Level Directory.

PROGRAM:
/* TLD */
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"null",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\\tc\\bgi");
display(root);
getch();
closegraph();
}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL){
(*root)=(node*)malloc(sizeof(node));
printf("Enter name of dir/file(under %s):",dname);
fflush(stdin);
gets((*root)->name);
if(lev==0||lev==1)
(*root)->ftype=1;
else
(*root)->ftype=2;
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
if(lev==0||lev==1)
{
if((*root)->level==0)
printf("How many users");
else
printf("How many files");
printf("(for%s):",(*root)->name);
scanf("%d",&(*root)->nc);
}
else
(*root)->nc=0;
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]),lev+1,(*root)-
>name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
{line(root->x,root->y,root->link[i]->x,root->link[i]->y);}
if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}}

APPLICATIONS:
• To store details of a department like CSE or ECE etc. in a college
which consists of two level directory like classes such as I year, II
year etc and sections like A, B etc.

• Multimedia databases can be implemented using two level


directories with help of binary tree structure.

• Categories of employees in a corporate can be classified as


technical and non-technical staff by using two level directories.

• Binomial distribution makes use of two level directories in


distribution of information among surplus users.

INFRENCE: THE STUDENT UNDERSTAND THE TWO LEVEL


DIRECTORY
QUESTIONS:

• What is contiguous allocation of disk space?


• What is command to delete a directory in UNIX?
• How do you create sub directories in UNIX?
• What are major methods of allocating disk space?
• What are advantages of two level directories?
• What is complete binary tree?
• Define index block?
• What is combination scheme?
Exp. No: 3 (c). Hierarchical Level Directory

AIM: Simulate file organization techniques for Hierarchical Level


Directory.
PROGRAM:

/* HLD */
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\\tc\\BGI");
display(root);
getch();
closegraph();
}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("Enter name of dir/file(under %s) : ",dname);
fflush(stdin);
gets((*root)->name);
printf("enter 1 for Dir/2 for file : ");
scanf("%d",&(*root)->ftype);
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("No of sub directories/files(for %s):",(*root)->name);
scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]),lev+1,(*root)-
>name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}
}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root !=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
}
APPLICATIONS:

• To provide access to data for military, where access is restricted


towards data based on their superiority.
• To store details of products in a department store that may contain
various categories like stationary, home needs and home
appliances etc.

• To maintain server and workstation list of remote sites that


correspond to an organization.

• Active directory which is a major application of hierarchical level


directory of users corresponding to their region and domain
group.

INFRENCE: The student understand the Hierarchical Level Directory.

QUESTIONS:

• What is agglomerative approach?


• What are the disadvantages of hierarchical level directory?
• How do we implement hierarchical directory in UNIX operating
system?
• Why hierarchial directory is is being widely used in organizations?
• What are applications of a tree?
• Define terminologies that we use for representing a tree?
• What is the height of a binary tree?
• What is root partition?

Exp. No: 4(a) CONTIGUOUS FILE ALLOCATION

AIM: Write a C Program to implement Sequential File Allocation


method.

ALGORITHM:

Step 1: Start the program.


Step 2: Get the number of memory partition and their sizes.
Step 3: Get the number of processes and values of block size for each
process.
Step 4: First fit algorithm searches all the entire memory block until a
hole which is big enough is encountered. It allocates that memory
block for the requesting process.
Step 5: Best-fit algorithm searches the memory blocks for the smallest
hole which can
be allocated to requesting process and allocates if.
Step 6: Worst fit algorithm searches the memory blocks for the largest
hole and allocates it to the process.
Step 7: Analyses all the three memory management techniques and
display the best algorithm which utilizes the memory resources
effectively and efficiently.
Step 8: Stop the program.
PROGRAM:4 a)

/* CONTIGUOUS FILE ALLOCATION */

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

main()
{
int n,i,j,b[20],sb[20],t[20],x,c[20][20];
clrscr();
printf("Enter no. of files:");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("Enter no. of blocks occupied by file%d",i+1);
scanf("%d",&b[i]);
printf("Enter the starting block of file%d",i+1);
scanf("%d",&sb[i]);
t[i]=sb[i];
for(j=0;j<b[i];j++)
c[i][j]=sb[i]++;
}

printf("Filename\tStart block\tlength\n");

for(i=0;i<n;i++)
printf("%d\t %d \t%d\n",i+1,t[i],b[i]);

printf("Enter file name:");


scanf("%d",&x);
printf("File name is: %d",x);
printf("length is:%d",b[x-1]);
printf("blocks occupied:");

for(i=0;i<b[x-1];i++)
printf("%4d",c[x-1][i]);
getch();
}
APPLICATIONS:

• Allocation of memory using array which is a best application for


sequential file allocation
• Data in magnetic tape or disk acts as another best application for
sequential file allocation.

• In an organization, where employee details are maintained,


sequential file allocation can be implemented in following aspects:

• Storing id’s of employees who belong to a department.


• Storing team id of team to which an employee belongs to.
• Storing name of employee corresponding to employee’s id
• Maintaining details of employee in a file

INFRENCE: the student can understand the file allocation using


Sequential File
Allocation method.

QUESTIONS:

• What is file?
• What is directory?
• What are attributes of file?
• How to manage free space?
• What is disk scheduling?
• What is drawback of sequential file allocation?
• List different file extensions?
• What is swapping?
Exp. No: 4 (b) LINKED FILE ALLOCATIONS
AIM: Write a C Program to implement Linked File Allocation method.
ALGRITHM:
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the
queue
Step 3: Now the new page is inserted at the tail of the queue
Step 4: Create a stack
Step 5: When the page fault occurs replace page present at the bottom
of the stack
Step 6: Stop the allocation.

PROGRAM:
/* LINKED FILE ALLOCATION */

#include<stdio.h>
#include<conio.h>
struct file
{
char fname[10];
int start,size,block[10];
}f[10];
main()
{
int i,j,n;
clrscr();
printf("Enter no. of files: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter file name: ");
scanf("%s",&f[i].fname);
printf("Enter starting block: ");
scanf("%d",&f[i].start);
f[i].block[0]=f[i].start;
printf("Enter no. of blocks: ");
scanf("%d",&f[i].size);
printf("Enter block numbers: ");
for(j=1;j<=f[i].size;j++)
{
scanf("%d",&f[i].block[j]);
}
}
printf("File\tstart\tsize\tblock\n");
for(i=0;i<n;i++)
{
printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size);
for(j=1;j<=f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d",f[i].block[j]);
printf("\n");
}
getch();
}
APPLICATIONS:
• In games like treasure hunt, clues are provided at each level of
game to find treasure which is a typical application of linked
allocation.

• An information repository acts as linked file allocator where page


content is linked from index that is stored in repository.

• Message passing between entities that percept real world also


follow linked file allocation.

• In facebook, data structure is maintained in different databases to


allocate surplus memory using linked file allocation.

INFRENCE: the student can understand the file allocation using


linked File Allocation method

QUESTIONS:

• What is link? Explain?


• What are the advantages of linked allocation?
• What is pointer?
• How data can be secured by using linked file allocation?
• How data can be allocated into the memory by using linked file
allocation?
• What is dynamic memory allocation?
• What are the disadvantages of linked file allocation?
• What is heap? Explain?

Exp. No: 4(c). INDEXED FILE ALLOCATION


AIM: Write a C Program to implement Indexed File Allocation method.

ALGORITHM:

Step 1: Start.
Step 2: Let n be the size of the buffer
Step 3: check if there are any producer
Step 4: if yes check whether the buffer is full
Step 5: If no the producer item is stored in the buffer
Step 6: If the buffer is full the producer has to wait
Step 7: Check there is any cosumer.If yes check whether the buffer is
empty
Step 8: If no the consumer consumes them from the buffer
Step 9: If the buffer is empty, the consumer has to wait.
Step 10: Repeat checking for the producer and consumer till required
Step 11: Terminate the process.

PROGRAM:

/* INDEXED FILE ALLOCATION */

#include<stdio.h>
#include<conio.h>
main()
{
int n,m[20],i,j,sb[20],s[20],b[20][20],x;
clrscr();
printf("Enter no. of files: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("Enter starting block and size of file%d:",i+1);
scanf("%d%d",&sb[i],&s[i]);
printf("Enter blocks occupied by file%d:",i+1);
scanf("%d",&m[i]);
printf("Enter blocks of file%d:",i+1);
for(j=0;j<m[i];j++)
scanf("%d",&b[i][j]);
}
printf("\nFile\t index\tlength\n");

for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\n",i+1,sb[i],m[i]);
}

printf("\nEnter file name:");


scanf("%d",&x);
printf("file name is:%d\n",x);
i=x-1;

printf("Index is:%d",sb[i]);
printf("Block occupied are:");

for(j=0;j<m[i];j++)
printf("%3d",b[i][j]);
getch();
}
APPLICATIONS:

• Organizations maintain the employee details in a file or record


based on their designation.

• Corporate companies maintain the information about the employee


based on their employee ID in company’s database.

• In lottery, winners are declared based on token number, where the


token acts as index that refers to a person.

• Hash tables will store data in its entries based on index value.
Data can be inserted into corresponding locations by performing
hash function on bucket value and key value that is to be entered
by the user.

INFRENCE: the student can understand the file allocation using


Indexed File Allocation method.

QUESTIONS:

• What is index? Explain?


• What are the advantages of indexed allocation?
• What is hash function?
• What are types of hash functions?
• How data can be allocated into the memory by using indexed file
allocation?
• What is bucket?
• What are the disadvantages of indexed file allocation?
• What is Key? Describe?
5.Program: write a c program to copy the contents of one file to another
using system calls
#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
int main(int args,char *ar[])
{
char *source=ar[1];
char *dest="def.txt";
char *buf=(char *)malloc(sizeof(char)*120);
int fd1,fd2;
fd1=open(source,O_CREAT,0744);
fd2=open(dest,O_CREAT,0744);
while(read(fd1,buf,120)!=-1)
{
printf("%s",buf);
//printf("Processing\n");
write(fd2,buf,120);
}
printf("Process Done");
close(fd1);
close(fd2);
}
Exp. No: 6 BANKER’S ALGORITHM FOR DEADLOCK
AVOIDANCE

AIM: A program to simulate the Bankers Algorithm for Deadlock


Avoidance.

THEORY:

When a new process enters a system, it must declare the maximum


number of instances of each resource type it needed. This number may
exceed the total number of resources in the system. When the user
requests a set of resources, the system must determine whether the
allocation of each resource will leave the system in safe state. If it will
the resources are allocation; otherwise the process must wait until some
other process release the resources.
Data structures

• n- Number of process, m-number of resource types.


• Available: Available[j]=k, k – instance of resource type Rj is
available.
• Max: If max [i, j]=k, Pi may request at most k instances resource
Rj.
• Allocation: If Allocation [i, j]=k, Pi allocated to k instances of
resource Rj
• Need: If Need[I, j]=k, Pi may need k more instances of resource
type Rj,
Need [I, j] =Max [I, j]-Allocation [I, j];
Safety Algorithm

• Work and Finish be the vector of length m and n respectively,


Work=Available and Finish[i] =False.
• Find an i such that both
• Finish[i] =False
• Need<=Work
If no such I exist go to step 4.
• work=work+Allocation, Finish[i] =True;
• If Finish [1] =True for all I, then the system is in safe state.

Resource request algorithm

• Let Request i be request vector for the process Pi, If request


i=[j]=k, then process Pi wants k instances of resource type Rj.

• If Request<=Need I go to step 2. Otherwise raise an error


condition.
• If Request<=Available go to step 3. Otherwise Pi must since the
resources are available.
• Have the system pretend to have allocated the requested resources
to process Pi by modifying the state as follows;
Available=Available-Request I;
Allocation I =Allocation+Request I;
Need i=Need i-Request I;

If the resulting resource allocation state is safe, the transaction is


completed and process Pi is allocated its resources. However, if the
state is unsafe, the Pi must wait for Request i and the old resource-
allocation state is restore.

ALGORITHM:

• Start the program.


• Get the values of resources and processes.
• Get the avail value.
• After allocation find the need value.
• Check whether it is possible to allocate.
• If it is possible then the system is in safe state.
• Else system is not in safety state.
• If the new request comes then check that the system is in safety.
• Or not if we allow the request.
• Stop the program.
PROGRAM:

/* BANKER’S ALGORITHM FOR DEADLOCK AVOIDANCE */

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

void main()
{

int n,r,i,j,k,p,u=0,s=0,m;
int block[10],run[10],active[10],newreq[10];
int max[10][10],resalloc[10][10],resreq[10][10];
int totalloc[10],totext[10],simalloc[10];
clrscr();
printf("Enter the no of processes:");
scanf("%d",&n);
printf("Enter the no of resource classes:");
scanf("%d",&r);
printf("Enter the total existed resource in each class:");

for(k=1;k<=r;k++)
scanf("%d",&totext[k]);
printf("Enter the allocated resources:");

for(i=1;i<=n;i++)
for(k=1;k<=r;k++)
scanf("%d",&resalloc);
printf("Enter the process making the new request:");
scanf("%d",&p);
printf("Enter the requested resource:");

for(k=1;k<=r;k++)
scanf("%d",&newreq[k]);
printf("Enter the process which are n blocked or running:");

for(i=1;i<=n;i++)
{
if(i!=p)
{
printf("process %d:\n",i+1);
scanf("%d%d",&block[i],&run[i]);
}
}
block[p]=0;
run[p]=0;

for(k=1;k<=r;k++)
{
j=0;

for(i=1;i<=n;i++)
{
totalloc[k]=j+resalloc[i][k];
j=totalloc[k];
}
}

for(i=1;i<=n;i++)
{
if(block[i]==1||run[i]==1)
active[i]=1;
else
active[i]=0;
}

for(k=1;k<=r;k++)
{
resalloc[p][k]+=newreq[k];
totalloc[k]+=newreq[k];
}

for(k=1;k<=r;k++)
{
if(totext[k]-totalloc[k]<0)
{
u=1;break;
}
}
if(u==0)
{

for(k=1;k<=r;k++)
simalloc[k]=totalloc[k];
for(s=1;s<=n;s++)

for(i=1;i<=n;i++)
{
if(active[i]==1)
{
j=0;

for(k=1;k<=r;k++)
{
if((totext[k]-simalloc[k])<(max[i][k]-resalloc[i][k]))
{
j=1;break;
}
}
}

if(j==0)
{
active[i]=0;
for(k=1;k<=r;k++)
simalloc[k]=resalloc[i][k];
}
}
m=0;
for(k=1;k<=r;k++)
resreq[p][k]=newreq[k];
printf("Deadlock willn't occur");
}

else
{
for(k=1;k<=r;k++)
{
resalloc[p][k]=newreq[k];
totalloc[k]=newreq[k];
}

printf("Deadlock will occur");


}
getch();
}

APPLICATIONS:

• Banker’s algorithm for deadlock avoidance is used in Flexible


Manufacturing System (FMS), to improve the performance of
operating system used in FMS.

• Many banks implement this algorithm to avoid loss of data and


resources, and to improve the performance of the system.
• This Banker’s algorithm for deadlock avoidance can be used in
the memory management to provide the access control.

• Banker’s algorithm for deadlock avoidance is used in many


corporate companies, to make use of their resources more
effectively.

INFERENCE: The student understands the deadlock problem, and how


to avoid the deadlock problem using Banker’s algorithm.

QUESTIONS:

• What is deadlock avoidance?


• What is resource allocation graph?
• How to avoid deadlock using banker’s algorithm?
• What are the limitations of Banker’s algorithm for deadlock
avoidance?
• List the advantages of Banker’s algorithm?
• What is safe state?
• What are the differences between allocation and need?
• What is safety algorithm?

Exp. No: 7 BANKER’S ALGORITHM FOR DEADLOCK


PREVENTION
AIM: A program to simulate Bankers Algorithm for Deadlock
Prevention.
THEORY:
Prevention Algorithm

• Work and Finish be the vector of length m and n respectively,


Work=Available and Finish[i] =False.
• Find an i such that both
• Finish[i] =False
• Need<=Work
If no such I exists go to step 4.
• work=work+Allocation, Finish[i] =True;
• if Finish[1]=True for all I, then the system is in safe state.

Resource request algorithm


• Let Request i be request vector for the process Pi, If request i=[j]=k,
then process Pi wants k instances of resource type Rj.

• if Request<=Need I go to step 2. Otherwise raise an error


condition.
• if Request<=Available go to step 3. Otherwise Pi must since the
resources are available.
• Have the system pretend to have allocated the requested resources
to process Pi by modifying the state as follows;
Available=Available-Request I;
Allocation I =Allocation+Request I;
Need i=Need i-Request I;
ALGORITHM:
Start the program.
• Get the values of resources and processes.
• Get the avail value.
• After allocation find the need value.
• Check whether it is possible to allocate.
• Check the resources are in under utilize or not.
• If it is under utilize then the system is not in safe state.
• Else system is in safety state.
• If the new request comes then check that the system is in safety.
• Or not if we allow the request.
• Stop the program.
PROGRAM:

/* BANKER’S ALGORITHM FOR DEADLOCK PREVENTION */

#include<stdio.h>
#include<conio.h>
void main()
{
int cl[10][10],al[10][10],av[10],i,j,k,m,n,c,ne[10][10],flag=0;
clrscr();
printf("\nEnter the matrix");
scanf("%d %d",&m,&n);
printf("\nEnter the clAIM matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&cl[i][j]);
}}
printf("\nEnter allocated matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&al[i][j]);
}}
printf("\nThe need matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
ne[i][j]=cl[i][j]-al[i][j];
printf("\t%d",ne[i][j]);
}
printf("\n");
}
printf("\nEnter avaliable matrix");
for(i=0;i<3;i++)
scanf("%d",av[i]);
printf("CLAIM matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",cl[i][j]);
}
printf("\n");
}
printf("\n allocated matrix:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("\t%d",al[i][j]);
}
printf("\n");
}
printf(" available matrix:\n");
for(i=0;i<3;i++)
{
printf("\t%d",av[i]);
}
for(k=0;k<m;k++)
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if(av[j]>=ne[i][j])
flag=1;
else
break;
if(flag==1&& j==n-1)
goto a;
}}
a: if(flag==0)
{
printf("unsafestate");
}
if(flag==1)
{
flag=0;
for(i=0;i<m;i++)
{
for(j=0;j<n;i++)
{
av[j]+=al[i][j];
al[i][j]=1;
}}
printf("\n safe state");
for(i=0;i<n;i++)
printf("\t available matrix:%d",av[i]);
}
getch();
}
APPLICATIONS:

• Banker’s algorithm for deadlock prevention used in Mainframe


computers like AS400, to perform tasks more effectively than other
computers.

• IBM OS/360 System makes use of preempted operating system, to


prevent the system from deadlock.

• To manage hardware and software resources efficiently in


organizations, this banker’s algorithm for deadlock prevention is
used.

• Cable operators make use of this banker’s algorithm for deadlock


prevention to broadcast the advertisements simultaneously.

INFERENCE: The student understands the deadlock problem, and how


to prevent the deadlock problem using Banker’s algorithm.
QUESTIONS:
• What is deadlock prevention?
• What are the conditions that are to be held to detect deadlock?
• What is mutual exclusion?
• What are the limitations of Banker’s algorithm for deadlock
prevention?
• What is circular wait?
• What is unsafe state?
• What are the methods to prevent deadlock?
• What is difference between preemption and non-preemption state?
Exp. No: 8(a) FIFO PAGE REPLACEMENT ALGORITHM

AIM: To implement page replacement algorithm FIFO (First In


First Out).
ALGORITHM:
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the
queue
Step 3: Now the new page is inserted at the tail of the queue

PROGRAM:

/* FIFO Page Replacement Algorithm */

#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
void main()
{
clrscr();
printf("\n \t\t\t FIFI PAGE REPLACEMENT ALGORITHM");
printf("\n Enter no. of frames....");
scanf("%d",&nof);
printf("Enter number of reference string..\n");
scanf("%d",&nor);
printf("\n Enter the reference string..");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\nThe given reference string:");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=1;i<=nof;i++)
frm[i]=-1;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference np%d->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}}
if(flag==0)
{
pf++;
victim++;
victim=victim%nof;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
}
printf("\n\n\t\t No. of pages faults...%d",pf);
getch();
}
APPLICATIONS:

• A queue of people at ticket-window: The person who comes first


gets the ticket first. The person who is coming last is getting the
tickets in last. Therefore, it follows first-in-first-out (FIFO)
strategy of queue.

• Vehicles on toll-tax Bridge: The vehicle that comes first to the toll
tax booth leaves the booth first. The vehicle that comes last leaves
last. Therefore, it follows first-in-first-out (FIFO) strategy of
queue.

• Phone answering system: The person who calls first gets a


response first from the phone answering system. The person who
calls last gets the response last. Therefore, it follows first-in-first-
out (FIFO) strategy of queue.

• Luggage checking machine: Luggage checking machine checks the


luggage first that comes first. Therefore, it follows FIFO principle
of queue.
• Patients waiting outside the doctor's clinic: The patient who comes
first visits the doctor first, and the patient who comes last visits the
doctor last. Therefore, it follows the first-in-first-out (FIFO)
strategy of queue.

INFERENCE: The student understands, page replacement concept,


FIFO (First In First Out) algorithm.

QUESTIONS:

• What is paging? Explain?


• What is page fault? When it occurs?
• Explain the concept of FIFO with the help of diagram?
• What are the drawbacks of FIFO?
• What are the Limitations of FIFO?
• Compare and Contrast in between FIFO and LIFO?
• What are the advantages of paging? List them?
• What are the differences in between FIFO and LFU?
Exp. No: 8(b) LRU PAGE REPLACEMENT ALGORITHM

AIM: To implement page replacement algorithm LRU (Least


Recently Used).

THEORY:

LRU (Least Recently Used) is selects the page that has not been
used for the longest period of time.

ALGORITHM:

Step 1: Create a queue to hold all pages in memory


Step 2: When the page is required replace the page at the head of the
queue
Step 3: Now the new page is inserted at the tail of the queue
Step 4: Create a stack
Step 5: When the page fault occurs replace page present at the bottom
of the stack

PROGRAM:

/* LRU Page Replacement Algorithm */

#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],lrucal[50],count=0;
int lruvictim();

void main()
{
clrscr();
printf("\n\t\t\t LRU PAGE REPLACEMENT ALGORITHM");
printf("\n Enter no. of Frames....");
scanf("%d",&nof);

printf(" Enter no. of reference string.. ");


scanf("%d",&nor);

printf("\n Enter reference string..");


for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\n\n\t\t LRU PAGE REPLACEMENT ALGORITHM ");
printf("\n\t The given reference string:");
printf("\n………………………………..");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=1;i<=nof;i++)
{
frm[i]=-1;
lrucal[i]=0;
}

for(i=0;i<10;i++)
recent[i]=0;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference NO %d->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}
}

if(flag==0)
{
count++;
if(count<=nof)
victim++;
else
victim=lruvictim();
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
recent[ref[i]]=i;
}
printf("\n\n\t No. of page faults...%d",pf);
getch();
}
int lruvictim()
{
int i,j,temp1,temp2;
for(i=0;i<nof;i++)
{
temp1=frm[i];
lrucal[i]=recent[temp1];
}
temp2=lrucal[0];
for(j=1;j<nof;j++)
{
if(temp2>lrucal[j])
temp2=lrucal[j];
}
for(i=0;i<nof;i++)
if(ref[temp2]==frm[i])
return i;
return 0;
}
APPLICATIONS:
• Stack, approach to implementing LRU replacement is to keep a
stack of page numbers. Whenever a page is referenced, it is
removed from the stack and put on the top.

• Counters are the one of the best application for Least recently used
(LRU) page replacement algorithm. In this least recent time will be
removed from the timer.

• In cache memory, the data stored in this memory will be replaced


if they are no longer periods of time used.

• Arranging of books or articles in the shelf involves placing the


book or article, which is least used in lower part of shelf.

INFERENCE: The student understands, page replacement


concept,LRU (Least Recently Used).

QUESTIONS:

• What is LRU?
• Why is the LRU used in page replacement?
• What is belady’s algorithm?
• What is LRU Approximation?
• What is stack? List its applications?
• Draw structure to implement LRU algorithm?
• Differentiate in between LRU and LFU?
• What are the drawbacks of LRU page replacement algorithm?
Exp. No: 8(c) OPTIMAL (LFU) PAGE REPLACEMENT
ALGORITHM

AIM: To implement page replacement algorithm Optimal page


replacement algorithm (LFU).

THEORY:

Optimal page replacement algorithm (LFU) means the page which


is not used for longest time. Here we select the page that will not be used
for the longest period of time.

ALGORITHM:

Step 1: Start the program


Step 2: Create a array
Step 3: When the page fault occurs replace page that will not be used
for the longest period of time
Step 4: Stop the program

PROGRAM:

/*OPTIMAL (LFU) page replacement algorithm*/

#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],optcal[50],count=0;
int optvictim();
void main()
{
clrscr();
printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHM");
printf("\n.................................");
printf("\nEnter the no. of frames: ");
scanf("%d",&nof);
printf("Enter the no. of reference string: ");
scanf("%d",&nor);
printf("Enter the reference string: ");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
clrscr();
printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHM");
printf("\n................................");
printf("\nThe given string");
printf("\n....................\n");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=0;i<nof;i++)
{
frm[i]=-1;
optcal[i]=0;
}
for(i=0;i<10;i++)
recent[i]=0;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\tref no %d ->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}
}
if(flag==0)
{
count++;
if(count<=nof)
victim++;
else
victim=optvictim(i);
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
}
printf("\n Number of page faults: %d",pf);
getch();
}
int optvictim(int index)
{
int i,j,temp,notfound;
for(i=0;i<nof;i++)
{
notfound=1;
for(j=index;j<nor;j++)
if(frm[i]==ref[j])
{
notfound=0;
optcal[i]=j;
break;
}
if(notfound==1)
return i;
}
temp=optcal[0];
for(i=1;i<nof;i++)
if(temp<optcal[i])
temp=optcal[i];
for(i=0;i<nof;i++)
if(frm[temp]==frm[i])
return i;
return 0;
}

APPLICATIONS:

• Cookie, approach to implementing LFU replacement is to keep a


track of web pages are surfing by a user. Whenever a web page is
referenced, it is put on the top and least referenced page is
removed from the history.
• Most of the users, they uses the apps for fast accessing of the
services, what they most use. If there is no space for important
apps, the infrequent apps are removed.

• Speed dial is another important application for LFU (optimal)


page replacement algorithm. In this method, most frequent callers
are added to speed dial list. The list is updated by removing of
infrequent callers with the frequent callers.

• The cable operators will prefers the channels, which are most
frequently used by the users. If there is no enough capacity for all
channels, the least preferred channels were removed by the
operator instead frequent channels.

INFERENCE: The student understands, page replacement concept,


Optimal page replacement algorithm (LFU). algorithm.
QUESTIONS:

• What is LFU?
• Why is the LFU used in page replacement?
• What are the countermeasures to Belady’s anomaly?
• What is main use of LFU (optimal) page replacement algorithm?
• What is page fault? Explain?
• Draw structure to implement LFU algorithm?
• Differentiate in between FIFO and LFU?
• What are the drawbacks of LFU page replacement algorithm?
Exp. No: 9(a) Paging Technique of memory management

AIM: To implement the Memory management technique- Paging.

ALGORITHM:

Step 1: Read all the necessary input from the keyboard.


Step 2: Pages - Logical memory is broken into fixed - sized blocks.
Step 3: Frames – Physical memory is broken into fixed – sized blocks.
Step 4: Calculate the physical address using the following
Physical address = (Frame number * Frame size) + offset
Step 5: Display the physical address.
Step 6: Stop the process.
PROGRAM:

/* Memory Management with Paging Technique */

#include <stdio.h>
#include <conio.h>
struct pstruct
{
int fno;
int pbit;
}ptable[10];

int pmsize,lmsize,psize,frame,page,ftable[20],frameno;

void info()
{
printf("\n\nMEMORY MANAGEMENT USING PAGING\n\n");
printf("\n\nEnter the Size of Physical memory: ");
scanf("%d",&pmsize);
printf("\n\nEnter the size of Logical memory: ");
scanf("%d",&lmsize);
printf("\n\nEnter the partition size: ");
scanf("%d",&psize);
frame = (int) pmsize/psize;
page = (int) lmsize/psize;
printf("\nThe physical memory is divided into %d no. of
frames\n",frame);
printf("\nThe Logical memory is divided into %d no. of
pages",page);
}
void assign()
{
int i;
for (i=0;i<page;i++)
{
ptable[i].fno = -1;
ptable[i].pbit= -1;
}
for(i=0; i<frame;i++)
ftable[i] = 32555;
for (i=0;i<page;i++)
{
printf("\n\nEnter the Frame number where page %d must be
placed: ",i);
scanf("%d",&frameno);
ftable[frameno] = i;
if(ptable[i].pbit == -1)
{
ptable[i].fno = frameno;
ptable[i].pbit = 1;
}
}
getch();
// clrscr();
printf("\n\nPAGE TABLE\n\n");
printf("Page Address Frame No. PresenceBit\n\n");
for (i=0;i<page;i++)
printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit);
printf("\n\n\n\tFRAME TABLE\n\n");
printf("Frame Address Page No\n\n");
for(i=0;i<frame;i++)
printf("%d\t\t%d\n",i,ftable[i]);
}
void cphyaddr()
{
int laddr,paddr,disp,phyaddr,baddr;
getch();
// clrscr();
printf("\n\n\n\tProcess to create the Physical Address\n\n");
printf("\nEnter the Base Address: ");
scanf("%d",&baddr);
printf("\nEnter theLogical Address: ");
scanf("%d",&laddr);

paddr = laddr / psize;


disp = laddr % psize;
if(ptable[paddr].pbit == 1 )
phyaddr = baddr + (ptable[paddr].fno*psize) + disp;
printf("\nThe Physical Address where the instruction present:
%d",phyaddr);
}
void main()
{
clrscr();
info();
assign();
cphyaddr();
getch();
}
APPLICATIONS:

• The SPARC architecture (with 32-bit addressing) supports a three-


level paging scheme, whereas the 32-bit Motorola 68030
architecture supports a four-level paging scheme.

• Solaris uses the system class to run kernel processes, such as the
scheduler and paging daemon.

• Loading of web pages from server to the clients is the best


application for paging technique.

• Routers they maintain tables like paging, when data came into
router, they gets an entry in the routing table. The packet is stored
in the routing table is to be processed by the router. Similarly, the
page that gets entry in the routing table will be processed by the
processor immediately.

INFERENCE: The student understands the concept paging for memory


management.
QUESTIONS:

• What is paging?
• What is demand paging?
• How the memory can be organized in paging?
• What are the advantages of paging technique?
• What is the difference between internal fragmentation and external
fragmentation?
• What is context switching?
• What are the disadvantages of paging technique?
• What is the difference between frame and page?
Exp. No 9: b) Segmentation Memory Allocation Technique

AIM: To implement the memory management policy-segmentation.

ALGORITHM:

Step 1: Start the program.


Step 2: Get the number of segments.
Step 3: get the base address and length for each segment.
Step 4: Get the logical address.
Step 5: check whether the segment number is within the limit, if not
display the error message.
Step 6: Check whether the byte reference is within the limit, if not
display the error message.
Step 7: Calculate the physical memory and display it.
Step 8: Stop the program.

PROGRAM:

/*MEMORY SEGMENT TABLE*/

#include <stdio.h>
#include <conio.h>
#include <math.h>
int sost;
void gstinfo();
void ptladdr();
struct segtab
{
int sno;
int baddr;
int limit;
int val[10];
}st[10];

void gstinfo()
{
int i,j;
printf("\n\tEnter the size of the segment table: ");
scanf("%d",&sost);

for(i=1;i<=sost;i++)
{
printf("\n\tEnter the information about segment: %d",i);
st[i].sno = i;
printf("\n\tEnter the base Address: ");
scanf("%d",&st[i].baddr);
printf("\n\tEnter the Limit: ");
scanf("%d",&st[i].limit);
for(j=0;j<st[i].limit;j++)
{
printf("Enter the %d address Value: ",(st[i].baddr +
j));
scanf("%d",&st[i].val[j]);
}
}
}
void ptladdr()
{
int i,swd,d=0,n,s,disp,paddr;
clrscr();
printf("\n\n\t\t\t SEGMENT TABLE \n\n");
printf("\n\t SEG.NO\tBASE ADDRESS\t LIMIT \n\n");
for(i=1;i<=sost;i++)
printf("\t\t%d
\t\t%d\t\t%d\n\n",st[i].sno,st[i].baddr,st[i].limit);
printf("\n\nEnter the logical Address: ");
scanf("%d",&swd);
n=swd;
while (n != 0)
{
n=n/10;
d++;
}

s = swd/pow(10,d-1);
disp = swd%(int)pow(10,d-1);

if(s<=sost)
{
if(disp < st[s].limit)
{
paddr = st[s].baddr + disp;
printf("\n\t\tLogical Address is: %d",swd);
printf("\n\t\tMapped Physical address is: %d",paddr);
printf("\n\tThe value is: %d",( st[s].val[disp] ) );
}
else
printf("\n\t\tLimit of segment %d is high\n\n",s);
}

else
printf("\n\t\tInvalid Segment Address \n");
}

void main()
{
char ch;
clrscr();
gstinfo();
do
{
ptladdr();
printf("\n\t Do U want to Continue(Y/N)");
flushall();
scanf("%c",&ch);
}while (ch == 'Y' || ch == 'y' );

getch();
}
APPLICATIONS:
• In ATM (Asynchronous transmission mode) networks, data is
stored in the form of segments, often they called as cells.

• To transmit the data over the networks using ISO/OSI reference


model’s transport layer the data, which is in packet format will be
segmented, when it passes through low capacity communication
media.

• IBM OS/360 and Intel Pentium use memory segmentation for


storing the large amount of information in uniform order.

• In many Colleges, day will be segmented to periods to maintain


uniform allocation of time to various subjects.

INFERENCE: The student understands the memory management


policy-segmentation.
QUESTIOS:

• What is segmentation?
• What are the advantages of segmentation?
• In what context does segmentation apply?
• What are the alternatives for memory segmentation?
• What is the basic idea for invention of memory segmentation?
• Describe the any real world memory segmentation technique?
• What are dichotomies are for memory segmentation?
• List the differences between segmentation and fragmentation?
10. write a cprogram to implement the 1s/sort command use named
pine

#include <stdio.h>
#include <string.h>

void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;

printf("Enter the value of n \n");


scanf("%d", &n);
printf("Enter %d names n", \n);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}
for (i = 0; i < n - 1 ; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
printf("\n----------------------------------------\n");
printf("Input NamestSorted names\n");
printf("------------------------------------------\n");
for (i = 0; i < n; i++)
{
printf("%s\t\t%s\n", tname[i], name[i]);
}
printf("------------------------------------------\n");
}

11.Program : write a c program to solve the Dining –Philospher


problem using semaphores
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#define N 5
#define THINKING 0
#define HUNGRY 1
#define EATING 2
#define LEFT (ph_num+4)%N
#define RIGHT (ph_num+1)%N
sem_t mutex;
sem_t S[N];

void * philospher(void *num);


void take_fork(int);
void put_fork(int);
void test(int);
int state[N];
int phil_num[N]={0,1,2,3,4};

int main()
{
int i;
pthread_t thread_id[N];
sem_init(&mutex,0,1);
for(i=0;i<N;i++)
sem_init(&S[i],0,0);
for(i=0;i<N;i++)
{
pthread_create(&thread_id[i],NULL,philospher,&phil_num[i]);
printf("Philosopher %d is thinking\n",i+1);
}
for(i=0;i<N;i++)
pthread_join(thread_id[i],NULL);
}
void *philospher(void *num)
{
while(1)
{
int *i = num;
sleep(1);
take_fork(*i);
sleep(0);
put_fork(*i);
}}
void take_fork(int ph_num)
{
sem_wait(&mutex);
state[ph_num] = HUNGRY;
printf("Philosopher %d is Hungry\n",ph_num+1);
test(ph_num);
sem_post(&mutex);
sem_wait(&S[ph_num]);
sleep(1);
}
void test(int ph_num)
{
if (state[ph_num] == HUNGRY && state[LEFT] != EATING &&
state[RIGHT] != EATING)
{
state[ph_num] = EATING;
sleep(2);
printf("Philosopher %d takes fork %d and
%d\n",ph_num+1,LEFT+1,ph_num+1);
printf("Philosopher %d is Eating\n",ph_num+1);
sem_post(&S[ph_num]);
}
}
void put_fork(int ph_num)
{
sem_wait(&mutex);
state[ph_num] = THINKING;
printf("Philosopher %d putting fork %d and %d
down\n",ph_num+1,LEFT+1,ph_num+1);
printf("Philosopher %d is thinking\n",ph_num+1);
test(LEFT);
test(RIGHT);
sem_post(&mutex);
}
Exp. No: 12 Write a c program to implement ipc two unrelated
processes using named pipe

AIM: Simulation of Shared Memory using Inter Process


Communication.

THEORY:

Shared Memory is a type of IPC where the two processes share


same memory chunk and use it for IPC. One process writes into that
memory and other reads it.
A process creates a shared memory segment using shmget(). The
original owner of a shared memory segment can assign ownership to
another user with shmctl(). It can also revoke this assignment. Other
processes with proper permission can perform various control functions
on the shared memory segment using shmctl(). Once created, a shared
segment can be attached to a process address space using shmat(). It
can be detached using shmdt() (see shmop()).

The attaching process must have the appropriate permissions


for shmat(). Once attached, the process can read or write to the
segment, as allowed by the permission requested in the attach operation.
A shared segment can be attached multiple times by the same process.

A shared memory segment is described by a control structure


with a unique ID that points to an area of physical memory. The
identifier of the segment is called the shmid. The structure definition for
the shared memory segment control structures and prototypews can be
found in <sys/shm.h>.
We develop two programs here that illustrate the passing of a
simple piece of memory (a string) between the processes if running
simulatenously:
shm_server.c
-- simply creates the string and shared memory portion.
shm_client.c
-- attaches itself to the created shared memory portion
PROGRAM:

/* SHMServer.C */

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 27

void die(char *s)


{
perror(s);
exit(1);
}

int main()
{
char c;
int shmid;
key_t key;
char *shm, *s;
key = 5678;

if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)


die("shmget");

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)


die("shmat");
/* Put some things into the memory for the other process to read */
s = shm;

for (c = 'a'; c <= 'z'; c++)


*s++ = c;
/* * Wait until the other process
* changes the first character of our memory
* to '*', indicating that it has read what
* we put there */

while (*shm != '*')


sleep(1);

exit(0);
}

/* SHMClient. C*/

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 27

void die(char *s)


{
perror(s);
exit(1);
}

int main()
{
int shmid;
key_t key;
char *shm, *s;
key = 5678;

if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)


die("shmget");

if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)


die("shmat");
//Now read what the server put in the memory.

for (s = shm; *s != '\0'; s++)


putchar(*s);
putchar('\n');
/**Change the first character of the
*segment to '*', indicating we have read
*the segment. */
*shm = '*';

exit(0);
}

APPLICATIONS:
• Shared memory is very helpful and productive for Web
APPLICATIONS.
• Shared memory is useful for security-critical APPLICATIONS and
authentication modules for Web servers.
• Almost all commercial software uses it.
INFERENCE: The student understands Simulation of Shared Memory
using Inter Process Communication.

QUESTIONS:

• What is shmat() & shmget()? What is the use of these methods?


• What is fork? List the advantages of fork?
• How the shared memory helps in IPC?
• List the limitations of shared memory?
• Give the web APPLICATIONS of shared memory?
• How to protect the shared memory?
• What is Commercial software?
• What authentication protocols are used in shared memory?

You might also like