0% found this document useful (0 votes)
38 views62 pages

Cse (DS) 2-2 Os Lab Manual 2024-25 VR23

The document is a lab manual for Operating Systems for the B. Tech II Year II Semester in the Department of CSE (Data Science) for the academic year 2024-25. It includes the vision and mission of the college and department, program outcomes, educational objectives, specific outcomes, and a list of experiments with aims, algorithms, programs, and conclusions. The experiments cover various topics such as UNIX/Linux system calls, CPU scheduling algorithms, and memory management techniques.

Uploaded by

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

Cse (DS) 2-2 Os Lab Manual 2024-25 VR23

The document is a lab manual for Operating Systems for the B. Tech II Year II Semester in the Department of CSE (Data Science) for the academic year 2024-25. It includes the vision and mission of the college and department, program outcomes, educational objectives, specific outcomes, and a list of experiments with aims, algorithms, programs, and conclusions. The experiments cover various topics such as UNIX/Linux system calls, CPU scheduling algorithms, and memory management techniques.

Uploaded by

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

DEPARTMENT OF CSE (DATA SCIENCE)

OPERATING SYSTEMS

LAB MANUAL

ACADEMID YEAR 2024-25 (VR23)

B. TECH – II YEAR – II SEMESTER

By

Mr. Ramana Reddy S


Asst. Professor
Mrs. ARUNA GAYATRI K
Asst. Professor

1
CONTENTS

S.No. PARTICULARS

1 VISION & MISSION OF THE COLLEGE

2 VISION & MISSION OF THE DEPARTMENT

3 PROGRAM OUTCOMES

4 PROGRAM EDUCATIONAL OBJECTIVES(PEO)

5 PROGRAM SPECIFIC OUTCOMES(PSO)

6 LIST OF EXPERIMENTS
EACH EXPERIMENT WITH
I) AIM II) ALGORITHM III) PROGRAM IV) OUTPUT
7
VI) CONCLUSION

2
COLLEGE VISION

To evolve into a center of excellence in Science & Technology through creative and
innovative practices in teaching-learning, promoting academic achievement & research
excellence to produce internationally accepted competitive and world class professionals who are
psychologically strong and emotionally balanced imbued with social consciousness and ethical
values.

COLLEGE MISSION

To provide high quality academic programmers, training activities, research facilities and
opportunities supported by continuous industry-institute interaction aimed at employability,
entrepreneurship, leadership and research aptitude among students and contribute to the
economic and technological development of the region, state and nation.

VISION OF THE DEPARTMENT

To develop Data Science Professionals through creative and innovative approaches to address
the present and future challenges of the modern computing world

MISSION OF THE DEPARTMENT

Educate students by expanding their knowledge in cutting – edge technologies to acquire


professional ethics. Impact quality education to build research & entrepreneurial eco system
using niche technologies

3
PROGRAM OUTCOMES (POs)

PO1.Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and
an engineering specialization to the solution of complex engineering problems.
PO2.Problem analysis: Identify, formulate review research literature and analyze complex engineering
problems reaching substantiated conclusions using first principle of mathematics, natural science and
engineering science.
PO3.Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations.
PO4.Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
PO5.Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modeling to complex engineering activities with an understanding of the
limitations.
PO6.The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
PO7.Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8.Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO9.Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
PO10.Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and receive clear instructions.
PO11.Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one's own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
PO12.Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.

4
PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

 To create and sustain a community of learning in which students acquire knowledge and apply in
their concerned fields with due consideration for ethical, ecological, and economic issues.
 To provide knowledge based services so as to meet the needs of the society and industry.
 To make the students understand, design and implement the concepts in multiple arenas.
 To educate the students in disseminating the research findings with good soft skills so as to become
successful entrepreneurs.

PROGRAM SPECIFIC OUTCOMES (PSOs)

 Professional Skills: Learn the basic concepts of Computer Science and Engineering and to apply
them to various areas, like Data Structures, Operating Systems, Computer Organization, Computer
Networks, Information Security etc., in the design and implementation of complex systems.
 Problem-Solving Skills: Solutions to complex Computer Science and Engineering problems, using
latest hardware and software tools, along with analytical skills to arrive at cost effective and
appropriate solutions.
 Entrepreneurship Skills and Career Management: Social- awareness & environmental-wisdom
along with ethical responsibility to lead a successful career and to sustain passion and zeal for real-
world applications using optimal resources as an Entrepreneur.

5
List of Experiments:

1. Write programs using the I/O system calls of UNIX/LINUX operating system (open, read, write, close,

fcntl, seek, stat, opendir, readdir)


2. Write C programs to simulate the following CPU Scheduling algorithms a) FCFS b) SJF c) Round
Robin d) priority

3. Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention.

4. Write a C program to implement the Producer – Consumer problem

1. Using semaphores with busy waiting using UNIX/LINUX system calls.

2. Using semaphores without busy waiting using UNIX/LINUX system calls.


5. Write C programs to illustrate the following IPC mechanisms a) Pipes b) FIFOs c) Message Queues d)
Shared Memory
6. Write C programs to simulate the following memory management techniques a) Paging b)
Segmentation

7. Write C programs to simulate Page replacement policies a) FCFS b) LRU c) Optimal

8. Write C programs to simulate File Allocation methods

6
1) Write programs using the I/O system calls of UNIX/LINUX operating system (open, read,
write, close, fcntl, seek, stat, opendir, readdir)

Aim:C program using open,read, write,close systemcalls


There are 5 basic system calls that Unix provides for file I/O.
1. Create: Used to Create a new empty file Syntax:
int creat(char *filename, mode_t mode)
filename:nameofthefilewhichyouwanttocreate mode
: indicates permissions of new file.
2. open:Used toOpen thefileforreading,writingorboth.
Syntax:intopen(char*path,intflags [ ,intmode] );
Path: path to file which you want to use
flags: How you like to use
O_RDONLY:readonly, O_WRONLY:writeonly, O_RDWR:readandwrite,
O_CREAT:create file if it doesn’t exist, O_EXCL: prevent creation if it already exists
3. close: Tells the operating system you are done with a file descriptor and Close the file which
pointed by fd.
Syntax:intclose(intfd);
fd :file descriptor
4. read: From the file indicated by the file descriptor fd, the read() function reads cnt bytes
ofinputintothememoryareaindicatedbybuf.Asuccessfulread()updatestheaccesstimeforthe file.
Syntax:intread(intfd,char*buf,intsize);
fd: file descripter
buf: buffer to read data from
cnt: length of buffer
5. write: Writes cnt bytesfrom bufto thefileorsocket associatedwith fd. cnt should not be
greaterthanINT_MAX(definedinthelimits.hheaderfile).Ifcntiszero,write()simplyreturns0 without
attempting any other action.
Syntax:intwrite(intfd,char*buf,intsize);
fd: file descripter
buf:buffertowritedatato
cnt: length of buffer
*Filedescriptoris integer that uniquelyidentifiesan open fileof the process.

7
Algorithm:
1. Starthe program.
2. OpenafileforO_RDWRforR/W,O_CREATEforcreatingafile,O_TRUNCfortruncate a file.
3. Usinggetchar(),readthecharacterandstored inthestring[]array.
4. Thestring[]arrayiswriteinto afilecloseit.
5. Then the first is opened for read onlymodeand read the characters and displayed itand
close the file.
6. Stop theprogram.

Program:
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
int main()
{
intn,i=0;
int f1,f2;
char c,strin[100]; f1=open("data",O_RDWR|O_CREAT|O_TRUNC);
while((c=getchar())!='\n')
{

strin[i++]=c;
}

strin[i]='\0';
write(f1,strin,i);
close(f1);
f2=open("data",O_RDONLY); read(f2,strin,0);
printf("\n%s\n",strin); close(f2);
return0;
}

Output:
Hai Hai
Conclusion:

Programs Executed successfully for all possible cases of Input.

8
a) Aim: C program using lseek

Lseek is a system call that is used to change the location of the read/write pointer of a file
descriptor. The location can be set either in absolute or relative terms.
Syntax: off_tlseek(intfildes,off_toffset,intwhence);
intfildes: The file descriptor of the pointer that is going to be moved.
off_t offset : The offset of the pointer (measured in bytes).
intwhence: Legal values for this variable are provided at the end which are:
SEEK_SET (Offset is to be measured in absolute terms),
SEEK_CUR (Offset is to be measured relative to the current location of the
pointer), SEEK_END (Offset is to be measured relative to the end of the file)

Algorithm:
1. Start the program
2. Open a file in read mode
3. Read the contents of the file
4. Use lseek to change the position of pointer in the read process
5. Stop

9
Program:

#include<stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include<sys/types.h>
int main()
{

int file=0;
if((file=open("testfile.txt",O_RDONLY))<-1)
return1;
char buffer[19];
if(read(file,buffer,19)!=19)return1;
printf("%s\n",buffer);
if(lseek(file,10,SEEK_SET)<0)return1;
if(read(file,buffer,19)!=19)return1;
printf("%s\n",buffer);
return0;
}

Output:

Conclusion:

Programs Executed successfully for all possible cases of Input.

10
b) Aim: C program using opendir(),closedir(), readdir()

The following are the various operations using directories

1. Creating directories.
Syntax:intmkdir(constchar*pathname,mode_tmode);
2. The ‘pathname’ argument is used for the name of the directory.
3. Opening directories
Syntax:DIR*opendir(constchar*name);

4. Reading directories.
Syntax:structdirent*readdir(DIR *dirp);
5. Removing directories.
Syntax:intrmdir(constchar*pathname);
6. Closing the directory.
Syntax:intclosedir(DIR *dirp);

7. Getting the current working directory.


Syntax:char*getcwd(char*buf,size_tsize);

Algorithm:
1. Start the program
2. Print a menu to choose the different directory operations
3. To create and remove a directory asks the user for name and create and remove the
same respectively.
4. To open a directory, check whether directory exists or not. If yes open the directory. Fit
does not exists print an error message.
5. Finally close the opened directory.
6. Stop

11
Program:
#include<stdio.h>
#include<fcntl.h>
#include<dirent.h>
main()
{

chard[10];intc,op;DIR*e;
struct dirent *sd;
printf("**menu**\n1.createdir\n2.removedir\n3.readdir\nenterurchoice");
scanf("%d",&op);
switch(op)
{

case1:printf("enterdirname\n");scanf("%s",&d);
c=mkdir(d,777);
if(c==1)
printf("dirisnotcreated");
else
printf("diris created"); break;
case2:printf("enterdirname\n");scanf("%s",&d);
c=rmdir(d);
if(c==1)
printf("dirisnotremoved");
else
printf("dirisremoved"); break;
case3:printf("enterdirnametoopen");
scanf("%s",&d);
e=opendir(d);
if(e==NULL)
printf("dirdoesnotexist");else
{

printf("direxist\n");while((sd=readdir(e))!=NULL)printf("%s\t",sd->d_name);

12
}

closedir(e);
break;
}

Output:

Conclusion:

Programs Executed successfully for all possible cases of Input.

13
2) Write C programs to simulate the following CPU Scheduling Algorithms:

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

a) FCFS(FirstComeFirst Serve)

Aim:Write a C program to implement the various CPU Scheduling mechanisms such as FCFS
scheduling.

Algorithm:

1: Start the process


2: Accept the number of processes in the readyQ
3: For each process in the readyQ, assign the process-id and accept the CPU-burst-time
4: Set the waiting of the first process as ‘0’ and its burst time as its turn around time
5: For each process in the ReadyQ, Calculate
a. Waitingtime for process(n)=waitingtime ofprocess (n-1) +Burst time ofprocess(n-1)
b. TurnaroundtimeforProcess(n)=waitingtimeofProcess(n)+Bursttimeforprocess(n)

6: Calculate
a. Averagewaitingtime =TotalwaitingTime/ Numberof process
b. AverageTurnaroundtime=TotalTurnaroundTime/Numberofprocess

7: Stop the process

14
Program:

#include<stdio.h>

intmain()
{
intbt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp; float avg_wt,avg_tat;
printf("Enter number of process:"); scanf("%d",&n);
printf("\nEnter Burst-Time:\n");
for(i=0;i<n;i++)
{

printf("p% d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}

wt[0]=0; //waiting time for first process will be zero


//calculate waiting time
for(i=1;i<n;i++)
{

wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=(float)total/n; //average waiting time


total=0;
printf("\nProcess\tBurstTime\tWaitingTime\tTurnaroundTime");
for(i=0;i<n;i++)
{

tat[i]=bt[i]+wt[i]; //calculateturnaroundtime
total+=tat[i];
printf("\np%d\t\t%d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

15
avg_tat=(float)total/n; //average turnaround time
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage TurnaroundTime=%f\n",avg_tat);
}

Output:

Conclusion:

Programs Executed successfully for all possible cases of Input.

16
b) SJF (Shortest Job First)
Aim: Write a C program to implement the various process scheduling mechanisms such as SJF
Scheduling.
Algorithm:

1: Start the process

2: Accept the number of processes in the ready Queue

3: For each process in the readyQ, assign the process-id and accept the CPU burst time

4: Start the ReadyQ according to the shortest Burst-time by sorting according to lowest to
highest burst time.
5: Set the waiting time of the first process as‘0’anditsturnaroundtimeasitsbursttime.
6: For each process in the ready queue, calculate
(a) Waitingtime for process(n)=waitingtime ofprocess (n-1)+Burst time ofprocess(n-1)
(b) TurnaroundtimeforProcess(n)=waitingtimeofProcess(n)+Burst timeforprocess(n)

7:Calculate
 Average waiting time = Total waiting Time/ Number of processes
 Average Turnaround time=Total Turnaround Time/Number of processes
8: Stop the process

17
Program:
#include<stdio.h>
intmain()
{
intbt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt, avg_tat;
printf("Enter number of Processes:");
scanf("%d",&n);
printf("\nEnterBurstTime:\n");
for(i=0;i<n;i++)
{

printf("p%d:",i+1);
scanf("%d", &bt[i]);
p[i]=i+1; //contains process number
}

//sorting burst-time in ascending order using selection-sort


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

pos=i;
for(j=i+1;j<n;j++)
{

if(bt[j]<bt[pos])
pos=j;
}
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0; //waiting-time for first process will be zero


//calculate waiting-time
for(i=1;i<n;i++)
{

18
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}

avg_wt=(float)total/n; //average waiting time


total=0;
printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{

tat[i]=bt[i]+wt[i]; //calculate turn-around time


total+=tat[i];
printf("\np%d\t\t%d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=(float)total/n; //average turnaround


time printf("\n\nAverage Waiting
Time=%f",avg_wt);
printf("\nAverageTurnaroundTime=%f\n",avg_
tat);
}

Output:

Conclusion: Programs Executed successfully for all possible cases of Input.

19
c) Round Robin Scheduling
Aim: Write a C program to implement the various process scheduling mechanisms such as
Round Robin Scheduling.

Algorithm
1: Start the process
2: Accept the number of processes in the readyQ and time-quantum (or) timeslice
3: For each process in the readyQ, assign the process-id and accept the CPU
burst-time.

4: Calculate the no. of time-slices for each process where, no. of time slice for
process(n)=burst time process(n)/time-slice.

5: If the burst-time is less than the time-slice, then the no. of time-slices=1.

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) Turnaroundtimeforprocess(n)=waitingtimeofprocess(n)+bursttimeofprocess(n)+the time
difference in getting CPU from process(n).

7: Calculate

(a) Averagewaitingtime = TotalwaitingTime/ Numberofprocess


(b) Average Turnaround time = Total Turnaround Time / Number of process Step 8: Stop the
proces

20
Program:
#include<stdio.h>
main()

int st[10],bt[10],wt[10],tat[10],n,tq;
inti,count=0,swt=0,stat=0,temp,sq=0;

float awt,atat;
printf("enterthenumberofprocesses");
scanf("%d",&n);
printf("enterthebursttimeofeachprocess/n");
for(i=0;i<n;i++)
{
printf(("p%d",i+1);

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

st[i]=bt[i];

printf("enterthetimequantum");
scanf("%d",&tq);
while(1)
{

for(i=0,count=0;i<n;i++)

temp=tq;
if(st[i]==0)
{
count++

continue;

21
if(st[i]>tq) st[i]=st[i]-tq;
else
if(st[i]>=0)
{
temp=st[i];
st[i]=0;
}
sq=sq+temp;
tat[i]=sq;
}

if(n==count)
break;
}
for(i=0;i<n;i++)

wt[i]=tat[i]-bt[i];
swt=swt+wt[i];
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("processno\tbursttime\twaitingtime\tturnaroundtime\n");
for(i=0;i<n;i++)
printf("%d\t\t %d\t\t %d\t\t %d\n",i+1,bt[i],wt[i],tat[i]);
printf("avgwttime=%f,avgturnaroundtime=%f",awt,atat);
}

22
Output:

Conclusion:

Programs Executed successfully for all possible cases of Input.

23
d) Priority Scheduling
Aim: Write a C program to implement the various process scheduling mechanisms
such as Priority Scheduling.

Algorithm:

1: Start the process

2: Accept the number of processes in the readyQ

3: For each process in the ready Q, assign the process id and accept the CPU burst time4:
Sort the ready queue according to the priority number.

5: Set the waiting of the first process as‘0’and its burst-time as its turnaround time
6: For each process in the Ready Q calculate
(e) Waitingtime for process(n)=waitingtimeofprocess (n-1)+Burst time ofprocess(n-1)
(f) TurnaroundtimeforProcess(n)=waitingtimeofProcess(n)+Bursttimeforprocess(n)

7: Calculate
(g) Averagewaitingtime = Total waitingTime/ Numberof processes
(h) AverageTurnaroundtime=TotalTurnaroundTime/Numberofprocesses
8: Stop the process

24
Program:

#include<stdio.h>

intmain()
{
intbt[20],p[20],wt[20],tat[20],pri[20],i,j,k,n,total=0,pos,temp; float avg_wt,avg_tat;
printf("Enternumberofprocess:");
scanf("%d",&n);
printf("\nEnterBurstTime:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}

printf("enter priority of the process");


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

p[i] =i;
//printf("Priority of Process");
printf("p%d ",i+1);
scanf("%d",&pri[i]);
}

for(i=0;i<n;i++)
for(k=i+1;k<n;k++
) if(pri[i] > pri[k])
{

temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];

25
pri[i]=pri[k];
pri[k]=temp;
}

wt[0]=0; //waiting-time for first process will be zero

//calculate waiting-time
for(i=1;i<n;i++)
{

wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=(float)total/n; //average waitingtime total=0;


printf("\nProcess\tBurstTime\tPriority\tWaitingTime\tTurnaroundTime");
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculateturnaroundtime
total+=tat[i];
printf("\np%d\t\t%d\t\t%d\t\t%d\t\t\t%d",p[i],bt[i],pri[i],wt[i],tat[i]);
}

avg_tat=(float)total/n; //average turnaround time


printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage TurnaroundTime=%f\n",avg_tat);
}

26
Output:

Conclusion:

Programs Executed successfully for all possible cases of Input.

27
3) Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention
a) Aim
Write a C program to simulate the Bankers Algorithm for Deadlock Avoidance.
Data structures:
1. n-Number of process, m-number of resource-types.
2. Available: Available[j]=k,k –instance of resource-type Rj is available.
3. Max:Ifmax[i,j]=k,Pi may request at-most k instances of resource Rj.
4. Allocation: If Allocation [i,j]=k,Pi allocated to k instances of resource Rj
5. Need:If Need[I,j]=k,Pi may need k more instances of resource-type Rj,
6. 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 goto step-4.
 work=work+Allocation,
Finish[i]=True;
 IfFinish[1] =True for all I, then the system is in safe state.

Resource request algorithm


1. Let Requesti be request vector for the process Pi, If requesti=[j]=k, then process Pi wants
k instances of resource type Rj.
2. If Request<=NeedIgotostep2.Otherwiseraise an error condition.
3. If Request<=Available gotostep3.OtherwisePimustsincetheresourcesareavailable.
4. Have the system pretend to have allocated the requested resource stop process Pi by
modifying the state as follows;
5. Available=Available-RequestI;
6. AllocationI=Allocation+Request I;
7. Needi=Needi-RequestI;

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.

28
Algorithm:
1. Start the program.
2. Get the values of resources and processes.
3. Get the available value.
4. After allocation find the need value.
5. Check whether it is possible to allocate.
6. If it is possible then the system is in safe state.
Else the system is not in safe state.
7. If the new request comes, then check that the system is in safe state or not, if we allow the
request.
8. Stop the program.

Program:
#include<stdio.h>
intmain ()
{

intallocated[15][15],max[15][15],need[15][15],avail[15],tres[15], work[15], flag[15];


intpno,rno,i,j,prc,count,t,total;
count = 0;
//clrscr();
printf("\nEnter number of processes:");
scanf ("%d", &pno);
printf("\nEnter number of resources:");
scanf ("%d", &rno);
for(i =1; i <=pno;i++)
{

flag[i]=0;
}

printf("\nEnter total numbers of each resource:");


for (i = 1; i <= rno; i++)
scanf("%d", &tres[i]);
printf("\nEnterMaxresourcesforeachprocess:");
for (i = 1; i <= pno; i++)
{

29
printf("\nforprocess%d:",i);
for (j = 1; j <= rno; j++)
scanf("%d", &max[i][j]);
}

printf("\nEnter allocated resources for each process:");


for (i = 1; i <= pno; i++)
{
printf("\nforprocess%d:",i);
for (j = 1; j <= rno; j++)
scanf("%d", &allocated[i][j]);
}

printf("\navailable resources:\n");
for (j = 1; j <= rno; j++)
{
avail[j] =0;
total= 0;
for(i =1; i <=pno; i++)
{
total+= allocated[i][j];
}
avail[j]=tres[j]-total;
work[j] = avail[j];
printf (" %d\t", work[j]);
}
do
{
for(i =1; i <=pno; i++)
{
for(j =1; j <=rno;j++)
{
need[i][j] =max[i][j]-allocated[i][j];
}
}
printf ("\n Allocated matrix Max
need");
for (i = 1; i <= pno; i++)
{
printf ("\n");
for(j =1; j <=rno;j++)
{
printf("%4d", allocated[i][j]);
}

30
printf ("|");
for(j =1; j <=rno;j++)
{
printf("%4d", max[i][j]);
}
printf ("|");
for(j =1; j <=rno;j++)
{
printf("%4d", need[i][j]);
}
}
prc=0;
for(i =1; i <=pno; i++)
{
if(flag[i] ==0)
{
prc=i;

for(j =1;j <=rno;j++)


{
if(work[j] <need[i][j])
{
prc=0;
break;
}
}
}
if(prc!=0)
break;
}
if(prc!=0)
{
printf("\nProcess%dcompleted",i);
count++;
printf("\nAvailablematrix:");
for (j = 1; j <= rno; j++)
{

work[j]+=allocated[prc][j];
allocated[prc][j] = 0;
max[prc][j]=0;
flag[prc]=1;
printf("%d",work[j]);
}

31
}

while(count !=pno&&prc!=0);
if(count==pno)
printf("\nThe system is in safe state!!");
else
printf("\nThe system is in an unsafe state!!");
return 0;
}

Output:

32
Conclusion: Programs Executed successfully for all possible cases of Input.

33
b) Aim
Write a C program to simulate Bankers Algorithm for Deadlock Prevention
Algorithm:
1. Start
2. Attacking Mutex condition: never grant exclusive access, but this may not be possible
for several resources.
3. Attacking Preemption: not something you want to do.
4. Attacking Hold & Wait condition: make a process hold at the most 1 resource at a time.
Make all the requests at the beginning. All or nothing policy. If you feel, retry. eg. 2-
phase locking 34
5. Attacking Circular Wait: Order all the resources. Make sure that the requests are issued
in the correct order so that there are no cycles present in the resource graph. Resources
numbered 1 ... n. Resources can be requested only in increasing order. ie. you cannot
request a resource whose no is less than any you may be holding.
6. Stop

Program:
#include<stdio.h>
intmax[10][10],alloc[10][10],need[10][10],avail[10],i,j,p,r,finish[10]={0},flag=0;
main( )
{

printf("\nSIMULATION OF DEADLOCK PREVENTION\n ");


printf("Enter no. of processes, resources\n");
scanf("%d%d",&p,&r);
printf("Enter allocation matrix");
for(i=0;i<p;i++)
for(j=0;j<r;j++)
scanf("%d",&alloc[i][j]);
printf("\nenter max matrix");
for(i=0;i<p;i++)/*reading the maximum matrix and available matrix*/
for(j=0;j<r;j++)
scanf("%d",&max[i][j]);
printf("\nenter available matrix");
for(i=0;i<r;i++) scanf("%d",&avail[i]);
for(i=0;i<p;i++) for(j=0;j<r;j++)
need[i][j]=max[i][j]-alloc[i][j]; fun(); /*calling
function*/ if(flag==0)
{if(finish[i]!=1)

34
{

printf("\nFailing: Mutual exclusion);


for(j=0;j<r;j++)
{ /*checking for mutual exclusion*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}
fun();
printf("\nBy allocating required resources to process%d deadlock is prevented", i);
printf("\n lack of preemption");
for(j=0;j<r;j++)
{

if(avail[j]<need[i][j])
avail[j]=need[i][j];
alloc[i][j]=0;
}

fun();
printf("\ndead lock is prevented by allocating needed resources");
printf("\nFailing: Hold & Wait condition");
for(j=0;j<r;j++)
{/*checking hold & wait condition*/
if(avail[j]<need[i][j])
avail[j]=need[i][j];
}

fun();
printf("\nAVOIDING ANYONE OF THE CONDITION, U CAN PREVENT DEADLOCK");
}

fun()
{

while(1)

35
{

for(flag=0,i=0;i<p;i++)
{

if(finish[i]==0)
{

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

if(need[i][j]<=avail[j])
continue;
else
break
;
}

if(j==r)
{

for(j=0;j<r;j++)
avail[j]+=alloc[i][j];
flag=1;
finish[i]=1; } } }

Output:

36
Conclusion:

Programs Executed successfully for all possible cases of Input.

37
4) Write a C program to implement the Producer–Consumer problem using semaphores using
UNIX/LINUX system calls.

Aim: Write a C program to implement the Producer–Consumer problem using semaphores using
UNIX/LINUX system calls.

Algorithm:
1. The Semaphore mutex, full &empty are initialized.
2. In the case of producer process
3. Produce an item in to temporary variable.
Ifthereisemptyspaceinthebuffercheckthemutexvalueforenterintothecriticalsection. If
the mutex value is 0, allow the producer to add value in the temporary variable to
the buffer.
4. In the case of consumer process
i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the mutex==0,
remove item from buffer
iii) Signal the mutex value and reduce the empty value by1.
iv) Consume the item.
5. Print the result.

38
Program:

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

Int mutex=1,full=0,empty=3,x=0; int

main ()
{
int n;
void producer ();
voidconsumer();
int wait (int);
intsignal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while (1)
{
printf("\nEnter your choice:");
scanf ("%d", &n);
switch (n)
{

case 1:
if((mutex==1)&&(empty!=0))
producer ();
else
printf("Buffer is full!!");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer ();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}

39
}

return0;
}

intwait(int s)
{

return(--s);
}

intsignal(ints)
{

return(++s);
}

voidproducer ()
{

mutex=wait(mutex);
full = signal (full);
empty=wait(empty);
x++;
printf("\nProducer produces the item%d",x);
mutex = signal (mutex);
}

void consumer()
{

mutex=wait(mutex);
full = wait (full);
empty=signal(empty);
printf("\nConsumer consumes item%d",x); x--;
mutex=signal(mutex);
}

40
Output:

Conclusion:

Programs Executed successfully for all possible cases of Input.

41
5. Write C programs to illustrate the following IPC mechanisms 1) Pipes 2) FIFO 3) Message
Quene 4) Shared Memory

Aim: Write C programs to illustrate the following IPC mechanisms


ALGORITHM:
1. Start the program.
2. Declare the variables.
3. Read the choice.
4. Create a piping process using IPC.
5. Assign the variable lengths
6. “strcpy” the message lengths.
7. To join the operation using IPC.
8. Stop the program.

Program: PIPE PROCESSING


#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#defineMSG_LEN64intmain(){ Int result;
intfd[2];
charmessage[MSG_LEN];
charrecvd_msg[MSG_LE];result=pipe(fd);
//Creating a pipe
//fd[0]is for reading and fd[1] is for writing
if(result<0)
{ perror("pipe ");
exit(1);
}
strncpy(message,"LinuxWorld!!",MSG_LEN);
result=write(fd[1],message,strlen(message));
if(result<0)
{perror("write");exit(2);
}
strncpy(message,"Understanding ",MSG_LEN);
result=write(fd[1],message,strlen(message));
if(result < 0)
{perror("write");exit(2);
}
strncpy(message,"Concepts of ",MSG_LEN); result=write(fd[1],message,strlen(message));
if (result <0)
{perror("write");exit(2);
}
strncpy(message,"Piping ", MSG_LEN); result=write(fd[1],message,strlen(message));
if (result < 0)
{perror("write"); exit(2);

42
}
result=read(fd[0],recvd_msg,MSG_LEN);
if(result<0)
{ perror("read"); exit(3);
}
printf("%s\n",recvd_msg);return0;
}

a) FIFO

Program:
#include <stdio.h>
#include <stdlib.h>
#include<sys/stat.>
#include <unistd.h>
#include<linux/stat.h>
#defineFIFO_FILE "MYFIFO"

int main(void)
{
FILE *fp;
char readbuf[80];
/*Create the FIFO if it does not exist*/
umask(0);
mknod(FIFO_FILE,S_IFIFO|0666,0);
while(1)
{
fp=fopen(FIFO_FILE,"r");
fgets(readbuf, 80, fp);
printf("Received string:%s\n",readbuf);
fclose(fp);
}
return(0);
}

#include <stdio.h>
#include<stdlib.h>
#defineFIFO_FILE "MYFIFO"
intmain(intargc,char*argv[])
{
FILE *fp;
if(argc !=2) {
printf("USAGE:fifoclient[string]\n");
exit(1);
}
if((fp=fopen(FIFO_FILE,"w"))==NULL)

43
{ perror("fopen");
exit(1);
}
fputs(argv[1], fp);
fclose(fp);
return(0);
}

C Program for Message Queue (Writer Process)


#include <stdio.h>
#include <sys/ipc.h>
#include<sys/msg.h>

//structureformessagequeue
struct mesg_buffer {
long
msg_type;charmsg_text[100];
} message;

int main()
{

key_tkey;
int msgid;
//ftoktogenerateuniquekey
key = ftok("progfile", 65);
//msgget creates a message-queue and returns identifier
msgid=msgget(key,0666|IPC_CREAT);
message.mesg_type = 1;
printf("Write Data : ");
gets(message.mesg_text);
//msg snd to send message
msgsnd(msgid,&message,sizeof(message),0);
//display the message
printf("Datasendis: %s\n",message.mesg_text);
return0;
}

44
C Program for Message-Queue (Reader Process)
#include <stdio.h>
#include <sys/ipc.h>
#include<sys/msg.h>
//structureformessagequeue
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;

int main()
{

key_tkey;
int
msgid;
//ftok to generate unique key
key = ftok("progfile", 65);
//msgget creates a message-queue and returns identifier
msgid = msgget(key, 0666 | IPC_CREAT);
//msgrcvtoreceivemessage
msgrcv(msgid, &message,sizeof(message),1, 0);
// display the message
printf("DataReceivedis:%s\n",
message.mesg_text);
// to destroy the message queue
msgctl(msgid,IPC_RMID,NULL);
return0;
}

C Program for Message-Queue (Reader Process)

#include <stdio.h>
#include<sys/ipc.h>
#include<sys/msg.h>
//structure for message queue
struct mesg_buffer {
long mesg_type;charmesg_text[100];
} message;

45
int main()
{

key_tkey;
int msgid;
//ftok to generate unique key
key = ftok("progfile", 65);
//msgget creates a message-queue and returns identifier
msgid=msgget(key,0666|IPC_CREAT);
//msgrcv to receive message
msgrcv(msgid, &message,sizeof(message),1, 0);
// display the message
printf("DataReceivedis:%s\n", message.mesg_text);
// to destroy the message queue
msgctl(msgid,IPC_RMID,NULL);
return0;
}

Output:

Conclusion: Programs Executed successfully for all possible cases of Input.

46
47
6. Write C programs to simulate the following Memory Management Techniques:

a) Paging

AIM:To write a C program to implement Memory Management using paging technique.

ALGORITHM:

Step1: Start the program.


Step2: Read the base address, page size, number of pages and memory limit.
Step3: If the memory limit < base address, display the memory limit is less than limit.
Step4: Create the page table with the number of pages and page address.
Step5: Read the page number and displacement value.
Step6: If the page number and displacement value is valid, add the displacement value to the address
corresponding to the page number and display the result.
Step7: Display the page is not found or displacement should be less than page size.
Step8: Stop the program.

Program:
#include<stdio.h> #include<conio.h> main()
{
int ms,ps,nop,np,rempages,i,j,x,y,pa,offset;
int s[10],fno[10][20];
printf("\nEnter the memory size -- ");
scanf("%d",&ms);
printf("\nEnter the pagesize--");
scanf("%d",&ps);
nop =ms/ps;
printf("\nThe no. of pages available in memory are--%d",nop);
printf("\nEnter number of processes -- ");
scanf("%d",&np);
rempages =nop;for(i=1;i<=np;i++)
{
printf("\nEnterno.ofpagesrequiredforp[%d]--",i);
scanf("%d",&s[i]);
if(s[i]>rempages)
{
printf("\nMemoryisFull"); break;
}
rempages = rempages - s[i];
printf("\nEnter page table for p[%d]---",i); for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}
printf("\nEnter Logical Address to find Physical Address");
printf("\nEnter process no. And page number and offset -- ");
scanf("%d %d %d",&x,&y, &offset);
if(x>np||y>=s[i]||offset>=ps)
printf("\nInvalid Processor Page Number or offset");
48
else
{
pa=fno[x][y]*ps+offset;
printf("\nThePhysicalAddressis-- %d",pa);
}

getch();
}

Output:

Conclusion:

Programs Executed successfully for all possible cases of Input.

49
b) Segmentation
Aim: To write a C program to implement Memory Management using Segmentation

Algorithm:
Step1: Start the program.

Step2: Read the base-address, number of segments, size of each segment, memory limit.

Step3: If memory address is less than the base address display “invalid memory limit”.

Step4: Create the segment table with the segment number and segment address and display it. Step5:
Read the segment number and displacement.

Step6: If the segment number and displacement is valid, compute the physical address and display the
same.

Step7: Stop the program.

Program:
Program:
#include<stdio.h>
#include<conio.h>
struct list
{

int seg; intbase;


int limit;
struct list *next;
} *p;
voidinsert(structlist*q,intbase,intlimit,intseg)
{ if(p==NULL)
{

p=malloc(sizeof(Structlist)); p-
>limit=limit;
p->base=base;
p->seg=seg;
p->next=NULL;
}

else
{
while(q->next!=NULL)
{
Q=q->next;
Printf(“yes”)
50
}
q->next=malloc(sizeof(Structlist)); q-
>next ->limit=limit;
q->next->base=base; q-
>next ->seg=seg;
q->next->next=NULL;
}
}
intfind(struct list*q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
returnq->limit;
}
intsearch(structlist*q,intseg)
{
while(q->seg!=seg)
{
q=q->next;
}
returnq->base;
}
main()
{
p=NULL;
intseg,offset,limit,base,c,s,physical;
printf(“Enter segment table/n”);
printf(“Enter-1assegmentvaluefortermination\n”); do
{
printf(“Entersegmentnumber”);
scanf(“%d”,&seg);
if(seg!=-1)
{
printf(“Enterbasevalue:”);
scanf(“%d”,&base);
printf(“Entervalueforlimit:”);
scanf(“%d”,&limit);
insert(p,base,lmit,seg);
}
}
while(seg!=-1)
printf(“Enteroffset:”);
scanf(“%d”,&offset);
printf(“Enterbsegmentationnumber:”);
scanf(“%d”,&seg);
c=find(p,seg);
s=search(p,seg); if(offset<c)
{
physical=s+offset;

51
printf(“Addressinphysicalmemory%d\n”,physical);
}

else
{

printf(“error”);
}

Output:

Entersegment table
Enter-1assegmentationvaluefortermination Enter
segment number:1
Enter base value:2000
Entervalueforlimit:100
Entersegmentnumber:2 Enter
base value:2500
Entervalueforlimit:100
Entersegmentationnumber:-1
Enter offset:90
Entersegment number:2
Addressinphysicalmemory2590

Entersegment table
Enter-1assegmentationvaluefortermination Enter
segment number:1
Enter base value:2000
Entervalueforlimit:100
Entersegmentnumber:2 Enter
base value:2500
Entervalueforlimit:100
Entersegmentationnumber:-1
Enter offset:90
Enter segment number:1
Addressinphysicalmemory20

Conclusion:

Programs Executed successfully for all possible cases of Input.

52
7) Write C programs to simulate Page replacement policies a) FCFS b) LRU c) Optimal

a) FCFS

AIM: To write Program to simulate FCFS Page Replacement Policy


Algorithm:
1. Start the process
2. Read number of pages n
3. Read page numbers into an array a[i]
4. Initialize avail[i]=0, to check Page Hit
5. Replace the page with circularQ, while re-placing check page availability in the frame Place
avail[i]=1 if page is placed in the frame Count page faults
6. Print the results.
7. Stop the process.

Program:
#include<stdio.h>
#include<conio.h>
intfr[3];
void main()
{
voiddisplay();
int i,j,page[12]={2,3,2,1,5,2,4,5,3,2,5,2};
int flag1=0,flag2=0,pf=0,frsize=3,top=0;
clrscr();
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0;flag2=0; for(i=0;i<12;i++)
{
if(fr[i]==page[j])
{
flag1=1;flag2=1; break;
}
}
if(flag1==0)
{
for(i=0;i<frsize;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];flag2=1;break;
}
}
}
if(flag2==0)
53
{
fr[top]=page[j];
top++;
pf++;
if(top>=frsize)
top=0;
}
display();
}
printf("Number of pagefaults:%d",pf+frsize);
getch();
}
Void display()
{
int i;
printf("\n");
for(i=0;i<3;i++)
printf("%d\t",fr[i]);
}

Output:
2-1-1
23-1
23-1
231
531
521
524
524
324
324
354
352
Number of page faults:9

Conclusion:

Programs Executed successfully for all possible cases of Input.

54
b) LRU

AIM: To write Programs to simulate LRU Page Replacement Policy


Algorithm:
1. Start the process
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process

Program:
#include<stdio.h>
#include<conio.h
>int fr[3];
void main()
{
voiddisplay();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
intindex,k,l,flag1=0,flag2=0,pf=0,frsize=3;
clrscr();
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0,flag2=0;
for(i=0;i<3;i++)
{
if(fr[i]==p[j])
{
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];flag2=1;
break;
}
}
}
55
if(flag2==0)
{
for(i=0;i<m;i++)
lg[i]=0;
for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-j;
break;
}
}
for(i=0;i<3;i++)
{
if(fs[i]==0)
index=i;
}
fr[index]=p[j];
pf++;
}
display();
}
printf("\nnoofpagefaults:%d",pf+frsize);
getch();
}
void display()
{
int i; printf("\n");
for(i=0;i<3;i++)
printf("\t%d", fr[i]);
}

Output:
2-1-1
23-1
23-1
231
251
251
254
254
354
352
352
352

No of page faults:7

Conclusion:

Programs Executed successfully for all possible cases of Input.


56
c) OPTIMAL

AIM: To write Program to simulate Optimal Page Replacement Policy


Algorthim:
1. Start program
2. Read number of pages and frames
3. Read each page value
4. Search for page in the frames; if not available allocate free frame
5. If no frame is free, Repalce the page with the page that is least used
6. Print page number of page faults
7. Stop process.

Program:
#include<stdio.h>
#include<conio.h
>int fr[3], n,
m;void
display();
voidmain()
{
inti,j,page[20],fs[10];
int max,found=0,lg[3],index,k,l,flag1=0,
flag2=0,pf=0; float pr;
clrscr();
printf("Enter length of the reference string:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter no of frames:");
scanf("%d",&m);
for(i=0;i<m;i++
) fr[i]=-1;
pf=m;
for(j=0;j<n;j++)
{
flag1=0;flag2=0;
for(i=0;i<m;i++)
{
if(fr[i]==page[j])
{
flag1=1;flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
57
fr[i]=page[j];flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<m;i++)
lg[i]=0;
for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-
j; break;
}
}
}
found=0;
for(i=0;i<m;i++)
{
if(lg[i]==0)
{
index=i;
found=1;
break;
}
}
if(found==0)
{
max=lg[0];
index=0;
for(i=0;i<m;i++)
{
if(max<lg[i])
{
max=lg[i];
index=i;
}
}
}
fr[index]=page[j];
pf++;
}
display();
}
printf("Number of page faults : %d\n", pf); pr=(float)pf/n*100;
printf("Pagefaultrate=%f\n",pr);getch();
}
void display()
{
int i;
58
for(i=0;i<m;i++)
printf("%d\t",fr[i]);
printf("\n");
}
for(j=0;j<n;j++)
{
flag1=0;flag2=0;
for(i=0;i<m;i++)
{
if(fr[i]==page[j])
{
flag1=1;flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<m;i++)
lg[i]=0;
for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-
j; break;
}
}
}
found=0;
for(i=0;i<m;i++)
{
if(lg[i]==0)
{
index=i;
found=1;
break;
}
}
if(found==0)
{
max=lg[0];
59
index=0;
for(i=0;i<m;i++)
{
if(max<lg[i])
{
max=lg[i];
index=i;
}
}
}
fr[index]=page[j];
pf++;
}
display();
}
printf("Number of page faults : %d\n", pf); pr=(float)pf/n*100;
printf("Pagefaultrate=%f\n",pr);getch();
}
voiddisplay()
{
int i;
for(i=0;i<m;i++)
printf("%d\t",fr[i]);
printf("\n");
}

Output:
Enter length of the reference string: 12
Enter the reference string: 1 2 3 4 1 2 5 1 2 3 4 5
Enter no of frames: 3
1-1-1
12-1
123
124
124
124
125
125
125
325
425
425
Number of page faults: 7 Page fault rate=58.333332

Conclusion:
Programs Executed successfully for all possible cases of Input.

60
8) Write C programs to simulate File Allocation methods
Aim: To write Programs to simulate File Allocation methods
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 it.
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:

#include < stdio.h>


#include<conio.h>
void main()
{
int f[50], i, st, len, j, c, k, count = 0;
clrscr();
for(i=0;i<50;i++)
f[i]=0;
printf("Files Allocated are : \n");
x: count=0;
printf(“Enter starting block and length of files: ”);
scanf("%d%d", &st,&len);
for(k=st;k<(st+len);k++)
if(f[k]==0)
count++;
if(len==count)
{
for(j=st;j<(st+len);j++)
if(f[j]==0)
{
f[j]=1;
printf("%d\t%d\n",j,f[j]);
}
if(j!=(st+len-1))
printf(” The file is allocated to disk\n");
}
else
printf(” The file is not allocated \n");
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if(c==1)
goto x;
else

61
exit();
getch();
}

Output:

Files Allocated are :


Enter starting block and length of files: 14 3
14 1
15 1
16 1
The file is allocated to disk
Do you want to enter more file(Yes - 1/No - 0)1
Enter starting block and length of files: 14 1
The file is not allocated
Do you want to enter more file(Yes - 1/No - 0)1
Enter starting block and length of files: 14 4
The file is not allocated
Do you want to enter more file(Yes - 1/No - 0)0

Conclusion:

Programs Executed successfully for all possible cases of Input.

62

You might also like