0% found this document useful (0 votes)
39 views

os lab manual 2022

Uploaded by

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

os lab manual 2022

Uploaded by

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

II B.

Tech II semester(CSE) OS WITH LINUX LAB

Lab Manual

Week-2

a.) echo "Enter a number"


read num

fact=1

while [ $num -gt 1 ]


do
fact=$((fact * num)) #fact = fact * num
num=$((num - 1)) #num = num - 1
done

echo $fact

output
bash fact

b)

#!bin/bash
h=$(date +"%H")
if [ $h -gt 6 -a $h -le 12 ]
then
echo good morning
elif [ $h -gt 12 -a $h -le 16 ]
then
echo good afternoon
elif [ $h -gt 16 -a $h -le 20 ]
then
echo good evening
else
echo good night
fi

ooutput
create a file with shell extention(filename.sh)

to compile use nano filename.sh


chmod +x filename.sh
bash filename.sh

CMR Institute of Technology Page 1


II B.Tech II semester(CSE) OS WITH LINUX LAB

Week-3

#include<sys/types.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[3])
{
int fd,i;
char buf[2];
fd=open(argv[1],O_RDONLY,0777);
if(fd==-argc)
{
printf("file open error");
}
else
{
printf("your program is printing data in the file \n");
while(i=read(fd,buf,1)>0)
{
printf("%c",buf[0]);
}
close(fd);
}
}

output

gcc week3.c
./a.out fact.c

CMR Institute of Technology Page 2


II B.Tech II semester(CSE) OS WITH LINUX LAB

week 4

a.) cp command
Exp 4: copy command
#include <stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/stat.h>
#include <string.h>
#define BUF_SIZE 32
#define FILE_NAME_LEN 200
int main(int argc, char *argv[])
{
FILE * file_to_read;
FILE * file_to_write;
char name_of_file_to_read[FILE_NAME_LEN+1];
char name_of_file_to_write[FILE_NAME_LEN+1];
char buf[BUF_SIZE];
size_t num_rec;
if(argc>3 || argc<3)
{
printf("Please Provide two arugments \n");
}
else{
if(access(argv[1],F_OK)<0)
{
printf("%s not found \n ",argv[1]);
}
/* Prepare the source file name */
strcpy(name_of_file_to_read, argv[1]);
/* Prepare the target file name */
if ( argc == 3 )
strcpy(name_of_file_to_write, argv[2]);
else
strcat(strcpy(name_of_file_to_write, name_of_file_to_read), ".fread");
/* Open source file in read-only mode */
if ( (file_to_read = fopen(name_of_file_to_read, "r")) == NULL )
{
fprintf(stderr, "Could not open file '%s' for reading\n",name_of_file_to_read);
return 3;
}
/* Open target file in write mode */
if ( (file_to_write = fopen(name_of_file_to_write, "w")) == NULL )
{
fprintf(stderr, "Could not open file '%s' for writing\n",
name_of_file_to_write);
fclose(file_to_read);
return 4;
}
while ( (num_rec = fread(buf, sizeof(char), BUF_SIZE, file_to_read) ) > 0 )

CMR Institute of Technology Page 3


II B.Tech II semester(CSE) OS WITH LINUX LAB

{
fwrite(buf, sizeof(char), num_rec, file_to_write);
if ( ferror(file_to_write) )
{
fprintf(stderr, "Error while writing into file '%s'\n",
name_of_file_to_write);
fclose(file_to_read);
fclose(file_to_write);
return 5;
}
}
if ( ferror(file_to_read) )
{
fprintf(stderr, "Error while reading the file '%s'\n", name_of_file_to_read);
fclose(file_to_read);
fclose(file_to_write);
return 6;
}
/* Close the files */
fclose(file_to_read);
fclose(file_to_write);
printf("File '%s' successfully copied to file '%s'\n", name_of_file_to_read,
name_of_file_to_write);
return 1;
}
}

CMR Institute of Technology Page 4


II B.Tech II semester(CSE) OS WITH LINUX LAB

b.) Implement in C the Unix command mv using system calls

#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main(int argc,char *argv[])
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
remove(file1);
close(fd1);
close(fd2);
}
Output:
[latha@localhost ~]$ cc week11c
[latha@localhost ~]$ ./a.out vowl2 ex
file1=vowl2 file2=ex
[latha@localhost ~]$ cat vowl2
cat: vowl2: No such file or directory
[latha@localhost ~]$ cat ex
apple
ball
ghj
latha bhavya REVATHI
CMRIT CMRCET CMREC CMRTC

CMR Institute of Technology Page 5


II B.Tech II semester(CSE) OS WITH LINUX LAB

week 5
C program to create a child process and allow the parent to display “parent” and the
child to display “child” on the screen

#include <stdio.h>
#include<stdlib.h>

#include <sys/wait.h> /* contains prototype for wait */

int main(void)

int pid;

int status;

printf("Hello World!\n");

pid = fork( );

if(pid == -1) /* check for error in fork */

perror("bad fork");

exit(1);

if (pid == 0)

printf("I am the child process.\n");

else { wait(&status); /* parent waits for child to finish */

printf("I am the parent process.\n");


return 0;

CMR Institute of Technology Page 6


II B.Tech II semester(CSE) OS WITH LINUX LAB

week6.c - program name


#include<stdio.h>
#include<unistd.h>

int main() {
int pipefds1[2], pipefds2[2];
int returnstatus1, returnstatus2;
int pid;
char pipe1writemessage[20] = "Hi";
char pipe2writemessage[20] = "Hello";
char readmessage[20];
returnstatus1 = pipe(pipefds1);

if (returnstatus1 == -1) {
printf("Unable to create pipe 1 \n");
return 1;
}
returnstatus2 = pipe(pipefds2);

if (returnstatus2 == -1) {
printf("Unable to create pipe 2 \n");
return 1;
}
pid = fork();

if (pid != 0)
{
close(pipefds1[0]);
close(pipefds2[1]);
printf("In Parent: Writing to pipe 1 – Message is %s\n", pipe1writemessage);

CMR Institute of Technology Page 7


II B.Tech II semester(CSE) OS WITH LINUX LAB

write(pipefds1[1], pipe1writemessage, sizeof(pipe1writemessage));


read(pipefds2[0], readmessage, sizeof(readmessage));
printf("In Parent: Reading from pipe 2 – Message is %s\n", readmessage);
}
else
{
close(pipefds1[1]);
close(pipefds2[0]);
read(pipefds1[0], readmessage, sizeof(readmessage));
printf("In Child: Reading from pipe 1 – Message is %s\n", readmessage);
printf("In Child: Writing to pipe 2 – Message is %s\n", pipe2writemessage);
write(pipefds2[1], pipe2writemessage, sizeof(pipe2writemessage));
}
return 0;
}

week6.sh - program name

gcc week6.c
./a.out

7) Write C programs to simulate the following CPU Scheduling algorithms:


a) FCFS b) priority

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
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 preempt the process p1 and assigned to process
p2.
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 cou will assign to some
other job only after the previous job has finished.
Scheduling methodology:
Through put: It means how many jobs are completed by the CPU with in a time period.
Turn around time: The time interval between the submission of the process and the time of
the completion is the turn around time.
Turn around 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

CMR Institute of Technology Page 8


II B.Tech II semester(CSE) OS WITH LINUX LAB

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 request 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.

A)FCFS 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 turnaround time
Step 5: for each process in the Ready Q calculate
(c) Waiting time for process(n)= waiting time of process(n-1)+Burst time of process(n-1)
(d) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for
process(n)
Step 6: Calculate
(e) Average waiting time = Total waiting Time / Number of process
(f) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{

CMR Institute of Technology Page 9


II B.Tech II semester(CSE) OS WITH LINUX LAB

int pid[10],bt[10],wt[10],tat[10],n,twt=0,ttat=0,i;
float awt,atat;
clrscr();
printf("Enter no.of processes:");
scanf("%d",&n);
printf("\n Enter burst times:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);
wt[0]=0;
tat[0]=bt[0];
for(i=1;i<n;i++)
{
wt[i]=tat[i-1];
tat[i]=bt[i]+wt[i];
}
for(i=0;i<n;i++)
{
ttat= ttat+tat[i];
twt=twt+wt[i];
}
printf("\n PID \t BT \t WT \t TAT");
for(i=0;i<n;i++)
printf("\n %d\t%d\t%d\t%d",i+1,bt[i],wt[i],tat[i]);
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\nAvg. Waiting Time=%f",awt);
printf("\nAvg. Turn around time=%f",atat);
getch();
}

OUTPUT:

CMR Institute of Technology Page 10


II B.Tech II semester(CSE) OS WITH LINUX LAB

B)PRIORITY 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, process priority and accept the
CPU burst time
Step 4: Start the Ready Q according the highest priority by sorting according to highest to
lowest priority.
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) Turn around time for Process(n)= waiting time of Process(n)+ Burst time for process(n)
Step 6: Calculate
(c) Average waiting time = Total waiting Time / Number of process
(d) Average Turnaround time = Total Turnaround Time / Number of process
Step 7: Stop the process

SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int pid[10],bt[10],pr[10],wt[10],tat[10],n,twt=0,ttat=0,i,j,t;
float awt,atat;
clrscr();
printf("Enter no.of processes:");
scanf("%d",&n);
printf("\n Enter burst times:");
for(i=0;i<n;i++)
scanf("%d",&bt[i]);

CMR Institute of Technology Page 11


II B.Tech II semester(CSE) OS WITH LINUX LAB

printf("\n Enter PID:");


for(i=0;i<n;i++)
scanf("%d",&pid[i]);
printf("\n Enter Priorities:");
for(i=0;i<n;i++)
scanf("%d",&pr[i]);
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;
}
}
}
wt[0]=0;
tat[0]=bt[0];
for(i=1;i<n;i++)
{
wt[i]=tat[i-1];
tat[i]=bt[i]+wt[i];
}
for(i=0;i<n;i++)
{
ttat= ttat+tat[i];
twt=twt+wt[i];
}
printf("\n PID PRIORITY \t BT \t WT \t TAT");
for(i=0;i<n;i++)
printf("\n %d\t%d\t%d\t%d\t%d",pid[i],pr[i],bt[i],wt[i],tat[i]);
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\nAvg. Waiting Time=%f",awt);
printf("\nAvg. Turn around time=%f",atat);
getch();
}

CMR Institute of Technology Page 12


II B.Tech II semester(CSE) OS WITH LINUX LAB

OUTPUT:

VIVA-VOCE:
1.What is an Operating system?
An operating system (OS) is system software that manages computer hardware and software
resources and provides common services for computer programs.
2.What is a process ?
A process is an instance of program in execution. The operating system is responsible for
managing all the processes that are running on a computer and allocated each process a
certain amount of time to use the processor.
3. What Are The Advantages Of A Multiprocessor System?
With an increased number of processors, there is considerable increase in throughput. It can also save
more money because they can share resources. Finally, overall reliability is increased as well.

CMR Institute of Technology Page 13


II B.Tech II semester(CSE) OS WITH LINUX LAB

4.Explain starvation and Aging?

Starvation or indefinite blocking is phenomenon associated with the Priority scheduling algorithms, in
which a process ready to run for CPU can wait indefinitely because of low priority.
Aging is a technique of gradually increasing the priority of processes that wait in the system for a
long time.
5.What are the functions of operating system?
The operating system controls and coordinates the use of hardware among the different processes and
applications. It provides the various functionalities to the users. The following are the main job of
operating system.

- Resource utilization
- Resource allocation
- Process management
- Memory management
- File management
- I/O management
- Device management
6.What do you know about interrupt?
Interrupt can be understood as a signal from a device causing context switch.
- To handle the interrupts, interrupt handlers or service routines are required.
- The address of each Interrupt service routine is provided in a list which is maintained in interrupt
vector.

CMR Institute of Technology Page 14


II B.Tech II semester(CSE) OS WITH LINUX LAB

8. Write C programs to simulate the following CPU Scheduling algorithms:


a) SJF b) RR

a) Step 1: Start the process


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

SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main(){
int pid[10],bt[10],wt[10],tat[10],n,twt=0,ttat=0,i,j,t;
float awt,atat;
clrscr();
printf("Enter no.of processes:");
scanf("%d",&n);
printf("\n Enter burst times:");

CMR Institute of Technology Page 15


II B.Tech II semester(CSE) OS WITH LINUX LAB

for(i=0;i<n;i++)
scanf("%d",&bt[i]);
printf("\n Enter PID:");
for(i=0;i<n;i++)
scanf("%d",&pid[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(bt[i]>bt[j])
{
t=bt[i];
bt[i]=bt[j];
bt[j]=t;

t=pid[i];
pid[i]=pid[j];
pid[j]=t;
}
}
}
wt[0]=0;
tat[0]=bt[0];
for(i=1;i<n;i++)
{
wt[i]=tat[i-1];
tat[i]=bt[i]+wt[i];
}
for(i=0;i<n;i++)
{
ttat= ttat+tat[i];
twt=twt+wt[i];
}
printf("\n PID \t BT \t WT \t TAT");
for(i=0;i<n;i++)

CMR Institute of Technology Page 16


II B.Tech II semester(CSE) OS WITH LINUX LAB

printf("\n %d\t%d\t%d\t%d",pid[i],bt[i],wt[i],tat[i]);
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\nAvg. Waiting Time=%f",awt);
printf("\nAvg. Turn around time=%f",atat);
getch();
}

B) ROUND ROBIN ALGORITHM:


Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue & time quantum or time slice
Step 3: For each process in the ready Q, assign the process id &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) Turn around 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

SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int ts,bt1[10],wt[10],tat[10],i,j=0,n,bt[10],ttat=0,twt=0,tot=0;
float awt,atat;
clrscr();
printf("Enter the number of Processes \n");
scanf("%d",&n);

CMR Institute of Technology Page 17


II B.Tech II semester(CSE) OS WITH LINUX LAB

printf("\n Enter the Timeslice \n");


scanf("%d",&ts);
printf("\n Enter the Burst Time for the process");
for(i=1;i<=n;i++)
{
scanf("%d",&bt1[i]);
bt[i]=bt1[i];
}
while(j<n)
{
for(i=1;i<=n;i++)
{
if(bt[i]>0)
{
if(bt[i]>=ts)
{
tot+=ts;
bt[i]=bt[i]-ts;
if(bt[i]==0)
{
j++;
tat[i]=tot;
}
}
else
{
tot+=bt[i];
bt[i]=0;
j++;
tat[i]=tot;
}
}
}
}
for(i=1;i<=n;i++)

CMR Institute of Technology Page 18


II B.Tech II semester(CSE) OS WITH LINUX LAB

{
wt[i]=tat[i]-bt1[i];
twt=twt+wt[i];
ttat=ttat+tat[i];
}
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\n PID \t BT \t WT \t TAT\n");
for(i=1;i<=n;i++) {
printf("\n %d \t %d \t %d \t %d \t\n",i,bt1[i],wt[i],tat[i]);
}
printf("\n The average Waiting Time=%f",awt);
printf("\n The average Turn around Time=%f",atat);
getch();
}

OUTPUT:

CMR Institute of Technology Page 19


II B.Tech II semester(CSE) OS WITH LINUX LAB

9.Write C programs to simulate the following file allocation strategies:


a) Sequential b) Linked c) Indexed
a) Sequential
Theory: The most common form of file structure is the sequential file in this type of file, a
fixed format is used for records. All records (of the system) have the same length,
consisting of the same number of fixed length fields in a particular order because the
length and position of each field are known, only the values of fields need to be stored,
the field name and length for each field are attributes of the file structure.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations to each in sequential order
a). Randomly select a location from availablelocation s1= random(100);
Step 5: Print the results file no, length, Blocks allocated.
Step 6: Stop the program
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
main()
{
int n,i,j,b[20],sb[20],t[20],x,c[20][20];
//clrscr();
printf("\t\t Sequential File allocation algorithm");
printf("\nEnter 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];

CMR Institute of Technology Page 20


II B.Tech II semester(CSE) OS WITH LINUX LAB

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\t %d \t\t%d\n",i+1,t[i],b[i]);
printf("Enter file name:");
scanf("%d",&x);
printf("\nFile name is:%d",x);
printf("\nlength is:%d",b[x-1]);
printf("\nblocks occupied:");
for(i=0;i<b[x-1];i++)
printf("%4d",c[x-1][i]);
getch();

OUTPUT:

Enter no. of files:3


Enter file name:A
Enter starting block:10
Enter no.of blocks:3
Enter block numbers:10
20
Enter file name:B
Enter starting block:20
Enter no.of blocks:3
Enter block numbers:30
32
Enter file name:C
Enter starting block:20
Enter no.of blocks:3
Enter block numbers:50
32
File start size block
A 10 3 10--->10--->20
B 20 3 20--->30--->32
C 20 3 20--->50--->32

CMR Institute of Technology Page 21


II B.Tech II semester(CSE) OS WITH LINUX LAB

b) Linked
In the chained method file allocation table contains a field which points to starting block of
memory. From it for each bloc a pointer is kept to next successive block. Hence, there is no
external fragmentation.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations by selecting a location randomly q= random(100);
a) Check whether the selected location is free .
b) If the location is free allocate and set flag=1 to the allocated locations.
q=random(100);
{
if(b[q].flag==0)
b[q].flag=1;
b[q].fno=j;
r[i][j]=q;
Step 5: Print the results file no, length ,Blocks allocated.
Step 6: Stop the program
SOURCE CODE:
#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("\t\t Linked File allocation algorithm");
printf("\nEnter 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]);
}

CMR Institute of Technology Page 22


II B.Tech II semester(CSE) OS WITH LINUX LAB

}
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=0;j<f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d\n",f[i].block[j]);
}
getch();
}

OUTPUT:
Enter no. of files:3
Enter file name:1
Enter starting block:50
Enter no.of blocks:5
Enter block numbers:10
20
60
70
Enter file name:1
Enter starting block:21
Enter no.of blocks:3
Enter block numbers:101
201
Enter file name:3
Enter starting block:31
Enter no.of blocks:3
Enter block numbers:234
456
File start size block
1 50 5 50--->10--->20--->60--->70
1 21 3 21--->101--->201
3 31 3 31--->234---> 456

c) Indexed
In the chained method file allocation table contains a field which points to starting block of
memory. From it for each bloc a pointer is kept to next successive block. Hence, there is no
external fragmentation
ALGORTHIM:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations by selecting a location randomly
q= random(100);
a) Check whether the selected location is free .
b) If the location is free allocate and set flag=1 to the allocated locations.
While allocating next location address to attach it to previous location

CMR Institute of Technology Page 23


II B.Tech II semester(CSE) OS WITH LINUX LAB

for(i=0;i0)
{}
}
p=r[i][j-1];
b[p].next=q;
}
Step 5: Print the results file no, length ,Blocks allocated.
Step 6: Stop the program
SOURCE CODE:
#include<stdio.h>
#include<conio.h>
main()
{
int n,m[20],i,j,sb[20],b[20][20],x;
//clrscr();
printf("\t\t Indexed File allocation algorithm");
printf("\nEnter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter index block of file%d:",i+1);
scanf("%d",&sb[i]);
printf("\nEnter length of 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("\nfile name is:%d",x);
printf("\nIndex is:%d",sb[x-1]);
printf("\nBlocks occupied are:");
for(j=0;j<m[x-1];j++)
printf("%4d",b[x-1][j]);
getch();
}

OUTPUT:
Enter no. of files:3
Enter file name:A
Enter starting block:10
Enter no.of blocks:5
Enter block numbers:10

CMR Institute of Technology Page 24


II B.Tech II semester(CSE) OS WITH LINUX LAB

44
12
34
Enter file name:B
Enter starting block:50
Enter no.of blocks:3
Enter block numbers:21
23
Enter file name:10
Enter starting block:20
Enter no.of blocks:5
Enter block numbers:56
65
43
32
File start size block
A 10 5 10--->10--->44--->12--->34
B 50 3 50--->21--->23
10 20 5 20--->56--->65--->43--->32

VIVA-VOCE:
1.Explain file allocation in Operating system?
A file allocation table (FAT) is a table that an operating system maintains on a hard disk
that provides a map of the clusters (the basic units of logical storage on a hard disk) that
a file has been stored in.
2.What is contiguous and noncontiguous memory allocations?
The basic difference between contiguous and noncontiguous memory allocationis
that contiguous allocation allocates one single contiguous block of memory to the process
whereas, the noncontiguous allocation divides the process into several blocks and place
them in the different address space of the memory.
3. Explain Sequential allocation?
In this scheme, each file occupies a contiguous set of blocks on the disk. For example, if
a file requires n blocks and is given a block b as the starting location, then the blocks
assigned to the file will be: b, b+1, b+2,……b+n-1. This means that given the starting block
address and the length of the file (in terms of blocks required.The directory entry for a file
with contiguous allocation contains
 Address of starting block
 Length of the allocated portion.

4.What is Linked allocation?


In linked allocation, each file is a linked list of disk blocks. The directory contains a
pointer to the first and optionally the last block of the file. For example, a file of 5 blocks
which starts at block 4, might continue at block 7, then block 16, block 10, and finally
block 27.
5.Explain Indexed allocation?
Provides solutions to problems of contiguous and linked allocation. A index block is created
having all pointers to files. Each file has its own index block which stores the addresses of
disk space occupied by the file. Directory contains the addresses of index blocks of files.
6.Explain FAT advantages and disadvantages?

CMR Institute of Technology Page 25


II B.Tech II semester(CSE) OS WITH LINUX LAB

Advantages of FAT:The main advantage of FAT is its efficient use of disk space. FAT can
place the parts of the file wherever they fit. File names can be up to 255 characters and file
extensions longer than 3 characters. Easy to recover file names that have been deleted.
Disadvantages of FAT:Overall performance slows down as more files are stored on the
drive. Drives can become fragmented quite easily. FAT lacks many of the security features in
NTFS such as being able to assign access rights to files and directories. It can also have file
integrity problems such as lost clusters, invalid files and directories and allocation errors.

10. Write C programs to simulate the following memory management techniques:


a) Paging b) Segmentation

Theory:Paging is an efficient memory management scheme because it is non-contiguous


memory allocation method. The basic idea of paging is the physical memory (main memory)
is divided into fixed sized blocks called frames, the logical address space is divided into fixed
sized blocks, called pages, but page size and frame size should be equal. The size of the
frame or a page is depending on operating system.
In this scheme the operating system maintains a data structure that is page table, it is
used for mapping purpose. The page table specifies the some useful information, it tells
which frames are there and so on. The page table consisting of two fields, one is the page
number and other one is frame number. Every address generated by the CPU divided into two
parts, one is page number and second is page offset or displacement. The pages are loaded
into available free frames in the physical memory.
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

SOURCE CODE:
#include<stdio.h>
#include<conio.h>

CMR Institute of Technology Page 26


II B.Tech II semester(CSE) OS WITH LINUX LAB

void main()
{
int i,j,temp,framearr[20],pages,pageno,frames,memsize,log,pagesize,prosize,base;
clrscr();
printf("Enter the Process size: ");
scanf("%d",&prosize);
printf("\nEnter the main memory size: ");
scanf("%d",&memsize);
printf("\nEnter the page size: ");
scanf("%d",&pagesize);
pages=prosize/pagesize;
printf("\nThe process is divided into %d pages",pages);
frames = memsize/pagesize;
printf("\n\nThe main memory is divided into %d frames\n",frames);
for(i=0;i<frames;i++)
framearr[i]=-1; /* Initializing array elements with -1*/
for(i=0;i<pages;i++)
{
pos: printf("\nEnter the frame number of page %d: ",i);
scanf("%d",&temp); /* storing frameno in temporary variable*/
if(temp>=frames) /*checking wether frameno is valid or not*/
{
printf("\n\t****Invalid frame number****\n");
goto pos;
}
/* storing pageno (i.e 'i' ) in framearr at framno (i.e temp ) index */
for(j=0;j<frames;j++)
if(temp==j)
framearr[temp]=i;
}
printf("\n\nFrameno\tpageno\tValidationBit\n------\t------\t----------");
for(i=0;i<frames;i++)
{
printf("\n %d \t %2d \t",i,framearr[i]);
if(framearr[i]==-1)

CMR Institute of Technology Page 27


II B.Tech II semester(CSE) OS WITH LINUX LAB

printf(" 0");
else
printf(" 1");
}
printf("\nEnter the logical address: ");
scanf("%d",&log);
printf("\nEnter the base address: ");
scanf("%d",&base);
pageno = log/pagesize;
for(i=0;i<frames;i++)
if(framearr[i]==pageno)
{
temp = i;
break;
}
j = log%pagesize; /* here 'j' is displacement */
temp = base + (temp*pagesize)+j; /* here lhs 'temp' is physical address and rhs
'temp' is frame number */
printf("\nPhysical address is : %d",temp);
getch();
}

OUTPUT:

CMR Institute of Technology Page 28


II B.Tech II semester(CSE) OS WITH LINUX LAB

b) Segmentation
Theory: A process is divided into Segments. The chunks that a program is divided into
which are not necessarily all of the same sizes are called segments. Segmentation gives
user’s view of the process which paging does not give. Here the user’s view is mapped to
physical memory.
Algorithm:
1. Input the number of memory blocks and their sizes and initializes all the blocks as
free.
2. Input the number of processes and their sizes.
3. Start by picking each process and check if it can be assigned to the current block, if
yes, allocate it the required memory and check for next process but from the block where we
left not from starting.

CMR Institute of Technology Page 29


II B.Tech II semester(CSE) OS WITH LINUX LAB

4. If the current block size is smaller then keep checking the further blocks.

SOURCE CODE:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,m,size,val[10][10],badd[20],limit[20],ladd;
//clrscr();
printf("\n \t\tSegmentation");
printf("\n Enter the size of the segment table:");
scanf("%d",&size);
for(i=0;i<size;i++)
{
printf("\nEnter infor about segment %d",i+1);
printf("\nEnter base address:");
scanf("%d",&badd[i]);
printf("\nEnter the limit:");
scanf("%d",&limit[i]);
for(j=0;j<limit[i];j++)
{
printf("\nEnter %d address values:",badd[i]+j);
scanf("%d",&val[i][j]);
}
}
printf("\n\n****SEGMENT TABLE****");
printf("\nseg.no\tbase\tlimit\n");
for(i=0;i<size;i++)
{
printf("%d\t%d\t%d\n",i+1,badd[i],limit[i]);
}
printf("\nEnter segment no.::");
scanf("%d",&i);
if(i>=size)
{
printf("invalid");
}
else
{
printf("\nEnter the logical address:");
scanf("%d",&ladd);
if(ladd>=limit[i])
printf("invalid");
else
{
m=badd[i]+ladd;
printf("\nmapped physical address is=%d",m);
printf("\nthe value is %d ",val[i][ladd]);
}

CMR Institute of Technology Page 30


II B.Tech II semester(CSE) OS WITH LINUX LAB

}
getch();
}
OUTPUT:
Enter segment number:1
Enter base value:2000
Enter value for limit:100
Enter segment number:2
Enter base value:2500
Enter value for limit:100
Enter segmentation number:-1
Enter offset:90
Enter segment number:2
Address in physical memory 2590

VIVA-VOCE:
1. What is the basic function of paging?

Paging is a memory management scheme that permits the physical address space of a process to be
noncontiguous. It avoids the considerable problem of having to fit varied sized memory chunks onto
the backing store.

2.What is fragmentation?

Fragmentation is memory wasted. It can be internal if we are dealing with systems that have fixed-
sized allocation units, or external if we are dealing with systems that have variable-sized allocation
units.

3.What is Thrashing?
Thrashing is a situation when the performance of a computer degrades or collapses.
Thrashing occurs when a system spends more time processing page faults than executing
transactions.

4.Differentiate between logical and physical address.

- Physical addresses are actual addresses used for fetching and storing data in main memory when the
process is under execution.
- Logical addresses are generated by user programs. During process loading, they are converted
by the loader into physical address.

5. Explain compaction.

During the process of loading and removal of process into and out of the memory, the free
memory gets broken into smaller pieces. These pieces lie scattered in the memory.
Compaction means movement of these pieces close to each other to form a larger chunk of
memory which works as a resource to run larger processes.
6.Explain Internal fragmentation and external fragmentation?

CMR Institute of Technology Page 31


II B.Tech II semester(CSE) OS WITH LINUX LAB

Internal fragmentation is the wasted space within each allocated block because of rounding
up from the actual requested allocation to the allocation granularity.
External fragmentation is the various free spaced holes that are generated in either memory
or disk space.

CMR Institute of Technology Page 32


II B.Tech II semester(CSE) OS WITH LINUX LAB

11.Write a C program to simulate Bankers Algorithm for Deadlock Avoidance

THEORY:Deadlock:
A process request the resources, the resources are not available at that time, so the
process enter into the waiting state. The requesting resources are held by another waiting
process, both are in waiting state, this situation is said to be Deadlock.
A deadlocked system must satisfied the following 4 conditions. These are:
(i) Mutual Exclusion: Mutual Exclusion means resources are in non-sharable mode only, it
means only one process at a time can use a process.
(ii) Hold and Wait: Each and every process is the deadlock state, must holding at least one
resource and is waiting for additional resources, that are currently being held by another
process.
(iii) No Preemption: No Preemption means resources are not released in the middle of the
work, they released only after the process has completed its task.
(iv) Circular Wait: If process P1 is waiting for a resource R1, it is held by P2, process P2 is
waiting for R2, R2 held by P3, P3 is waiting for R4, R4 is held by P2, P2 waiting for resource
R3, it is held by P1.
P1 R1 P2 R2 P3 R4 P2 R3

Deadlock Avoidance: It is one of the method of dynamically escaping from the deadlocks. In
this scheme, if a process request for resources, the avoidance algorithm checks before the
allocation of resources about the state of system. If the state is safe, the system allocate the
resources to the requesting process otherwise (unsafe) do not allocate the resources. So taking
care before the allocation said to be deadlock avoidance.
Banker’s Algorithm: It is the deadlock avoidance algorithm, the name was chosen because
the bank never allocates more than the available cash.
Available: A vector of length ‘m’ indicates the number of available resources of each type. If
available[j]=k, there are ‘k’ instances of resource types Rj available.
Allocation: An nxm matrix defines the number of resources of each type currently allocated
to each process. If allocation[i,j]=k, then process Pi is currently allocated ‘k’ instances of
resources type Rj.
Max: An nxm matrix defines the maximum demand of each process. If max[i,j]=k, then Pi
may request at most ‘k’ instances of resource type Rj.
Need: An nxm matrix indicates the remaining resources need of each process. If need[I,j]=k,
then Pi may need ‘k’ more instances of resource type Rj to complete this task. There fore,
Need[i,j]=Max[i,j]-Allocation[I,j]
Safety Algorithm
1. Work and Finish be the vector of length m and n respectively, Work=Available and
Finish[i] =False.
2. Find an i such that both Finish[i] =False Need<=Work
If no such I exists go to step 4.
3. work=work+Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.
Resource request algorithm

CMR Institute of Technology Page 33


II B.Tech II semester(CSE) OS WITH LINUX LAB

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.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the resources are available.
3. 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 restored.
ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether it’s possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. Or not if we allow the request.
10. Stop the program.

SOURCE CODE:
#include<stdio.h>
#include<conio.h>
int k,rq[10],i,j,count,temp=0,R[10],n,r,max[10][10], alloc[10][10],need[10]
[10],tr[10],p,q,avail[10],availb[10][10],availa[10][10];
void main()
{clrscr();
printf("enter no of process:");
scanf("%d",&n);
printf("\nenter no of resources:");
scanf("%d",&r);
for(i=1;i<=n;i++)
{
printf("process %d",i);

CMR Institute of Technology Page 34


II B.Tech II semester(CSE) OS WITH LINUX LAB

for(j=1;j<=r;j++)
{
printf("maximum value of resource:%d",i);
scanf("%d",&max[i][j]);
}
for(j=1;j<=r;j++)
{
printf("allocated from resource %d:",i);
scanf("%d",&alloc[i][j]);
}
}
for(i=1;i<=r;i++)
{
printf("enter total value of resource %d",i);
scanf("%d",&tr[i]);
}for(i=1;i<=n;i++)
{
for(j=1;j<=r;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
}}
printf("\nresources\tallocated\tneeded\n");
for(i=1;i<=n;i++)
{printf("p%d\t",i);
for(j=1;j<=r;j++)
{printf("%d",max[i][j]);
}printf("\t");
for(j=1;j<=r;j++)
{printf("%d",alloc[i][j]);
}
printf("\t");
for(j=1;j<=r;j++)
{
printf("%d",need[i][j]);
}printf("\n");

CMR Institute of Technology Page 35


II B.Tech II semester(CSE) OS WITH LINUX LAB

}
R[1]=0;
for(j=1;j<=r;j++)
{
for (i=1;i<=n;i++)
{ R[j]=R[j]+alloc[i][j];
}
avail[j]=tr[j]-R[j];
}
printf("total\t avail\n");
for(i=1;i<=r;i++)
{
printf("%d",tr[i]);
} printf("\t");
for(i=1;i<=r;i++)
{
printf("%d",avail[i]);
}
for(i=1;i<=n;i++)
{ count=0;
for(j=1;j<=r;j++)
{
if(avail[j]>=need[i][j])
{count=count+1;
if(count==r)
{
printf("the above sequence is a safe sequence");
q=i,p=i;
goto pos;
}
}
}temp=temp+1;
}
if(temp==n)
{

CMR Institute of Technology Page 36


II B.Tech II semester(CSE) OS WITH LINUX LAB

printf("\ndead lock");
exit();
}
pos:printf("\n\tavailb\tavaila\n");
printf("p%d\t",p);
for(i=1;i<=r;i++)
{
availb[p][i]=avail[i]-need[p][i];
printf("%d",availb[p][i]);
} printf("\t");
for(i=1;i<=r;i++)
{
availa[p][i]=max[p][i]+availb[p][i];
printf("%d",availa[p][i]);
}
printf("\n");
for(i=1;i<=n;i++)
{
if(i!=q)
{printf("p%d\t",i);
for(j=1;j<=r;j++)
{
availb[i][j]=availa[p][j]-need[i][j];
printf("%d",availb[i][j]);
}printf("\t");
for(j=1;j<=r;j++)
{
availa[i][j]=availb[i][j]+max[i][j];
printf("%d",availa[i][j]);
}
p=i;
printf("\n");
}
}
printf("enter the process to be requested");

CMR Institute of Technology Page 37


II B.Tech II semester(CSE) OS WITH LINUX LAB

scanf("%d",&k);
printf("\nenter the request value");
for(i=1;i<=r;i++)
{
scanf("%d",&rq[i]);
}
count=0;
for(i=1;i<=r;i++)
{
if(need[k][i]>=rq[i]&&avail[i]>=rq[i])
{
count=count+1;
if(count==r)
{
for(i=1;i<=r;i++)
{
avail[i]=avail[i]-rq[i];
}
}
}
}temp=0;
for(i=1;i<=n;i++)
{
count=0;
if(i!=k)
{
for(j=1;j<=r;j++)
{
if(need[i][j]>=avail[j])
{
count=count+1;
if(count==r)
{
printf("request granted\n");
exit();

CMR Institute of Technology Page 38


II B.Tech II semester(CSE) OS WITH LINUX LAB

}
}
}
}
temp=temp+1;
}
if(temp==n)
{
printf("request rejected");
exit();
}
getch();
}

OUTPUT:

CMR Institute of Technology Page 39


II B.Tech II semester(CSE) OS WITH LINUX LAB

VIVA-VOCE:
1.What is deadlock?
Deadlock is a situation when two or more processes wait for each other to finish and none of them
ever finish. Consider an example when two trains are coming toward each other on same track and

CMR Institute of Technology Page 40


II B.Tech II semester(CSE) OS WITH LINUX LAB

there is only one track, none of the trains can move once they are in front of each other. Similar
situation occurs in operating systems when there are two or more processes hold some resources and
wait for resources held by other(s).

2.What are the necessary conditions for deadlock?


Mutual Exclusion: There is a resource that cannot be shared.
Hold and Wait: A process is holding at least one resource and waiting for another resource which is
with some other process.
No Preemption: The operating system is not allowed to take a resource back from a process until
process gives it back.
Circular Wait: A set of processes are waiting for each other in circular form.
3.What is resource allocation graph?
A resource allocation graph tracks which resource is held by which process and which
process is waiting for a resource of a particular type. It is very powerful and simple tool to
illustrate how interacting processes can deadlock. If a process is using a resource, an
arrow is drawn from the resource node to the process node. If a process is requesting a
resource, an arrow is drawn from the process node to the resource node.
4.Explain safe state?
A state is safe if the system can allocate all resources requested by all processes ( up to
their stated maximums ) without entering a deadlock state. ... If a safe sequence does not
exist, then the system is in an unsafe state, which MAY lead to deadlock.
5.What is a critical section?
It is a section of code which can be executed only by one process at a time.

6.What is the purpose of Banker's algorithm?


The banker's algorithm is a resource allocation and deadlock avoidance algorithmthat tests
for safety by simulating the allocation for predetermined maximum possible amounts of all
resources, then makes an “s-state” check to test for possible activities, before deciding
whether allocation should be allowed to continue

CMR Institute of Technology Page 41


II B.Tech II semester(CSE) OS WITH LINUX LAB

12. Write C programs to simulate the following Page Replacement Techniques:


a) FIFO b) LRU c) OPTIMAL
THEORY:
a) FIFO (First in First Out) algorithm: FIFO is the simplest page replacement algorithm, the
idea behind this is, “Replace a page that page is oldest page of main memory” or “Replace
the page that has been in memory longest”. FIFO focuses on the length of time a page has
been in the memory rather than how much the page is being used.
b) LRU (Least Recently Used): the criteria of this algorithm is “Replace a page that has been
used for the longest period of time”. This strategy is the page replacement algorithm looking
backward in time, rather than forward.
c) LFU (Least Frequently Used): The least frequently used algorithm “select a page for
replacement, if the page has not been used for the often in the past” or “Replace page that
page has smallest count” for this algorithm each page maintains as counter which counter
value shows the least count, replace that page. The frequency counter is reset each time is
page is loaded.
A)FIFO Algorithm:
1. Start
2. Read the number of frames
3. Read the number of pages
4. Read the page numbers
5. Initialize the values in frames to -1
6. Allocate the pages in to frames in First in first out order.
7. Display the number of page faults.
8. Stop
SOURCE CODE:
#include<stdio.h>
void main()
{
int i,j,n,a[50],frame[10],fno,k,avail,pagefault=0;
printf("\nEnter the number of Frames : ");
scanf("%d",&fno);
printf("\nEnter number of reference string :");
scanf("%d",&n);
printf("\n Enter the Reference string :\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<fno;i++)
frame[i]= -1;
j=0;

CMR Institute of Technology Page 42


II B.Tech II semester(CSE) OS WITH LINUX LAB

printf("\n FIFO Page Replacement Algorithm\n\n The given reference string is:\n\n");
for(i=0;i<n;i++)
{
printf(" %d ",a[i]);
}
printf("\n");
for(i=0;i<n;i++)
{
printf("\nReference No %d-> ",a[i]);
avail=0;
for(k=0;k<fno;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j = (j+1) % fno;
pagefault++;
for(k=0;k<fno;k++)
if(frame[k]!=-1)
printf(" %2d",frame[k]);
}
printf("\n");
}
printf("\nPage Fault Is %d",pagefault);
}

OUTPUT:

CMR Institute of Technology Page 43


II B.Tech II semester(CSE) OS WITH LINUX LAB

B) LRU Algorithm:
1. Start
2. Read the number of frames
3. Read the number of pages
4. Read the page numbers
5. Initialize the values in frames to -1
6. Allocate the pages in to frames by selecting the page that has not been used for the longest
period of time.
7. Display the number of page faults.

CMR Institute of Technology Page 44


II B.Tech II semester(CSE) OS WITH LINUX LAB

8. Stop
SOURCE CODE:
#include<stdio.h>
void main()
{
int i,j,l,max,n,a[50],frame[10],flag,fno,k,avail,pagefault=0,lru[10];
printf("\nEnter the number of Frames : ");
scanf("%d",&fno);
printf("\nEnter number of reference string :");
scanf("%d",&n);
printf("\n Enter the Reference string :\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<fno;i++)
{
frame[i]= -1;
lru[i] = 0;
}
printf("\nLRU Page Replacement Algorithm\n\nThe given reference string is:\n\n");
for(i=0;i<n;i++)
{
printf(" %d ",a[i]);
}
printf("\n");
j=0;
for(i=0;i<n;i++)
{
max = 0;
flag=0;
printf("\nReference No %d-> ",a[i]);
avail=0;
for(k=0;k<fno;k++)
if(frame[k]==a[i])
{
avail=1;

CMR Institute of Technology Page 45


II B.Tech II semester(CSE) OS WITH LINUX LAB

lru[k]=0;
break;
}
if(avail==1)
{
for(k=0;k<fno;k++)
if(frame[k]!=-1)
++lru[k];
max = 0;
for(k=1;k<fno;k++)
if(lru[k]>lru[max])
max = k;
j = max;
}
if(avail==0)
{
lru[j]=0;
frame[j]=a[i];
for(k=0;k<fno;k++)
{
if(frame[k]!=-1)
++lru[k];
else
{
j = k;
flag = 1;
break;
}
}
if(flag==0){
max = 0;
for(k=1;k<fno;k++)
if(lru[k]>lru[max])
max = k;
j = max;

CMR Institute of Technology Page 46


II B.Tech II semester(CSE) OS WITH LINUX LAB

}
pagefault++;
for(k=0;k<fno;k++)
if(frame[k]!=-1)
printf(" %2d",frame[k]);
}
printf("\n");
}
printf("\nPage Fault Is %d",pagefault);
}

OUTPUT:

CMR Institute of Technology Page 47


II B.Tech II semester(CSE) OS WITH LINUX LAB

C) Optimal Algorithm:
1. Start
2. Read the number of frames
3. Read the number of pages
4. Read the page numbers
5. Initialize the values in frames to -1
6. Allocate the pages in to frames by selecting the page that will not be used for the longest
period of time.
7. Display the number of page faults.
8. Stop
SOURCE CODE:
#include<stdio.h>
int main()
{
int i,j,l,min,flag1,n,a[50],temp,frame[10],flag,fno,k,avail,pagefault=0,opt[10];
printf("\nEnter the number of Frames : ");
scanf("%d",&fno);
printf("\nEnter number of reference string :");
scanf("%d",&n);
printf("\n Enter the Reference string :\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

CMR Institute of Technology Page 48


II B.Tech II semester(CSE) OS WITH LINUX LAB

for(i=0;i<fno;i++)
{
frame[i]= -1;
opt[i]=0;
}
printf("\n Optimal Page Replacement Algorithm\n\nThe given reference string is:\n\n");
for(i=0;i<n;i++)
printf(" %d ",a[i]);
printf("\n");
j=0;
for(i=0;i<n;i++)
{
flag=0;
flag1=0;
printf("\nReference No %d-> ",a[i]);
avail=0;
for(k=0;k<fno;k++)
if(frame[k]==a[i])
{
avail=1;
break;
}
if(avail==0)
{
temp = frame[j];
frame[j]=a[i];
for(k=0;k<fno;k++)
{
if(frame[k]==-1)
{
j = k;
flag = 1;
break;
}
}

CMR Institute of Technology Page 49


II B.Tech II semester(CSE) OS WITH LINUX LAB

if(flag==0)
{
for(k=0;k<fno;k++)
{
opt[k]=0;
for(l=i;l<n;l++)
{
if(frame[k]==a[l])
{
flag1 = 1;
break;
}
}
if(flag1==1)
opt[k] = l-i;
else
{
opt[k] = -1;
break;
}
}
min = 0;
for(k=0;k<fno;k++)
if(opt[k]<opt[min]&&opt[k]!=-1)
min = k;
else if(opt[k]==-1)
{
min = k;
frame[j] = temp;
frame[k] = a[i];
break;
}
j = min;
}
pagefault++;

CMR Institute of Technology Page 50


II B.Tech II semester(CSE) OS WITH LINUX LAB

for(k=0;k<fno;k++)
if(frame[k]!=-1)
printf(" %2d",frame[k]);
}
printf("\n");
}
printf("\nPage Fault Is %d",pagefault);
return 0;
}

OUTPUT:

VIVA-VOCE:
1.What is a page fault?
A page fault occurs when a program attempts to access data or code that is in its address
space, but is not currently located in the system RAM.
2.Why do we use page replacement algorithms?

CMR Institute of Technology Page 51


II B.Tech II semester(CSE) OS WITH LINUX LAB

Whenever a new page is referred and not present in memory, page fault occurs and
Operating System replaces one of the existing pages with newly needed page.
3.Explain virtual memory?
Virtual memory is a memory management capability of an OS that uses hardware and
software to allow a computer to compensate for physical memory shortages by temporarily
transferring data from random access memory (RAM) to disk storage. Virtual address space
is increased using active memory in RAM and inactive memory in hard disk drives (HDDs)
to form contiguous addresses that hold both the application and its data.
4.Explain LRU with example.
Consider the following reference string as an example for better understanding of the LRU

algorithm.

CMR Institute of Technology Page 52

You might also like