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

OS Lab Programs

os lab

Uploaded by

Charan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

OS Lab Programs

os lab

Uploaded by

Charan Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Department of CSE (Artificial Intelligence and Machine Learning)

Operating System Laboratory Manual (BCS303)


(Scheme 2022-2023)

By,
Rekha K P
ASSISTANT PROFESSOR
Department of CSE (AI & ML), RLJIT
Department of CS&E (Artificial Intelligence and Machine Learning)
Vision

To empower the students with knowledge and skills to develop the competency in the field of Artificial
Intelligence and Machine Learning.

Mission

M1: To craft the students with Novel and Intellectual skills to capability in the field of Artificial Intelligence
and Machine Learning.

M2: To train the students to have Professional career in the field of AI and ML and zeal for Higher Studies
and Research.

Programme Specific Outcomes (PSOs)

PSO1: Students will have the ability to understand analyse and demonstrate the knowledge of Human
cognition, Artificial Intelligence, Machine Learning in terms of real world problems to meet the challenges
of future.

PSO2: Students will have the knowledge of software, Hardware, Algorithms, Modelling Networking and
Application Development.

PSO3: Students will have the ability to develop computational knowledge using Innovative tools and
techniques to solve problems in the areas related to Machine learning and Artificial Intelligence.

Programme Educational Objectives (PEOs)

PEO1: Graduates will have Prospective careers in the field of AI and ML.

PEO2: Graduates will have good Leadership Qualities, Self Learning abilities and zeal for higher studies
and Research.

PEO3: Graduates will follow Ethical Practices and exhibit high level of professionalism by participating
and addressing Technical, Business and Environmental challenges.
Programme Outcomes (PO)
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. 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.
4. 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.
5. 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.
6. 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.
7. 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.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
10. 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.
11. 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.
12. 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.
GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to starting
time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to
the lab with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab
session.
b. Laboratory Record updated up to the last session experiments and other
utensils (if any) needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems,
which should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during
the lab sessions. Misuse of the equipment, misbehaviors with the staff and systems
etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out ;
if anybody found loitering outside the lab / class without permission during working
hours will be treated seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she
leaves the lab after completing the task (experiment) in all aspects. He/she must
ensure the system / seat is kept properly.

HOD Principal
PROGRAM NO.1

PROCESS SYSTEM CALLS:

AIM: Develop a C program to implement the process system calls


(fork(),exec(),wait(),create process ,terminate process)

Description: System calls are essential functions provided by the operating system to
facilitate the interaction between user programs and the underlying hardware.

fork(): The fork() system call is used to create a new process (child process) that is a copy
of the current process (parent process). It duplicates the parent process, including its
memory, file descriptors, and program counter. After the fork(), both the parent and
child processes run independently, and they can communicate with each other via
interprocess communication mechanisms.

exec(): The exec() system call is used to replace the current process's code and memory
with a new program. It loads a new program into the current process's address space,
effectively replacing the existing program. This is often used to start a different
program within an existing process, for example, when a shell runs a command.

wait(): The wait() system call is used to make a parent process wait for the termination of
its child process. It allows a parent process to suspend its execution until one of its
child processes exits. This is useful for coordinating the execution of multiple
processes and for handling the exit status of child processes.

exit() :The exit() system call is used to terminate the current process and return an exit
status to the parent process.

Dept. of CSE(AI( & ML), RLJIT Page 1


SOURCE CODE:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
// Fork a child process
pid_t pid = fork();

if (pid < 0)
{
perror("Fork failed");
exit(EXIT_FAILURE);
}

else if (pid == 0)
{
// Child process
printf("Child process is running (PID: %d)\n", getpid());

// Execute a command in the child process using exec


char *args[] = {"ls", "-l", NULL};
if (execvp("ls", args) == -1) {
perror("Exec failed");
exit(EXIT_FAILURE);
}
}
else
{
// Parent process
printf("Parent process is waiting for the child to finish (PID: %d)\n", getpid());

// Wait for the child process to finish


int status;
wait(&status);

Dept. of CSE(AI( & ML), RLJIT Page 2


if (WIFEXITED(status))
{
printf("Child process (PID: %d) exited with status %d\n", pid,
WEXITSTATUS(status));
}
else
{
printf("Child process (PID: %d) did not exit normally\n", pid);
}

printf("Parent process is exiting (PID: %d)\n", getpid());


}
return 0;
}

Dept. of CSE(AI( & ML), RLJIT Page 3


PROGRAM NO.2

CPU SCHEDULINGALGORITHMS

A). FIRST COME FIRST SERVE:


AIM: To write a c program to simulate the CPU scheduling algorithm First Come
First Serve (FCFS).

DESCRIPTION:

To calculate the average waiting time using the FCFS algorithm first the waiting
time of the first process is kept zero and the waiting time of the second process is the burst
time of the first process and the waiting time of the third process is the sum of the burst
times of the first and the second process and so on. After calculating all the waiting times
the average waiting time is calculated as the average of all the waiting times. FCFS mainly
says first come first serve the algorithm which came first will be served first.

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 name and the 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
a). Waiting time (n) = waiting time (n-1) + Burst time (n-b).
b). Turnaround time (n)= waiting time(n)+Burst time(n).

Step 6: Calculate
a) Average waiting time = Total waiting Time / Number of process.
b) Average Turnaround time = Total Turnaround Time / Number of process .
Step 7: Stop the process.

Dept. of CSE(AI( & ML), RLJIT Page 4


SOURCE CODE:

#include<stdio.h>
#include<conio.h>
void main()
{
int bt[20], wt[20], tat[20], i, n; float wtavg, tatavg;
clrscr();
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND
TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround
Time -- %f", tatavg/n);
getch();

Dept. of CSE(AI( & ML), RLJIT Page 5


Dept. of CSE(AI( & ML), RLJIT Page 6
B). SHORTEST JOB FIRST:

AIM: To write a program to stimulate the CPU scheduling algorithm Shortest job first
(Non- Preemption).

DESCRIPTION:

To calculate the average waiting time in the shortest job first algorithm the sorting of
the process based on their burst time in ascending order then calculate the waiting time of
each process as the sum of the bursting times of all the process previous or before to that
process.

ALGORITHM:

Step 1: Start the process.


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

Dept. of CSE(AI( & ML), RLJIT Page 7


SOURCE CODE :

#include<stdio.h>
#include<conio.h>
void main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
clrscr();
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;

temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND
TIME\n");

Dept. of CSE(AI( & ML), RLJIT Page 8


for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
getch();
}

Dept. of CSE(AI( & ML), RLJIT Page 9


C). ROUND ROBIN:

AIM: To simulate the CPU scheduling algorithm round-robin.


DESCRIPTION:

To aim is to calculate the average waiting time. There will be a time slice, each
process should be executed within that time-slice and if not it will go to the waiting
state so first check whether the burst time is less than the time-slice. If it is less than it
assign the waiting time to the sum of the total times. If it is greater than the burst-time
then subtract the time slot from the actual burst time and increment it by time-slot and
the loop continues until all the processes are completed.

ALGORITHM:

Step 1: Start the process.


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

Dept. of CSE(AI( & ML), RLJIT Page 10


SOURCE CODE:

#include<stdio.h>
void main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
clrscr();
printf("Enter the no of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-
ct[i]; att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);

Dept. of CSE(AI( & ML), RLJIT Page 11


printf("\nThe Average Waiting time is -- %f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
getch();
}

Dept. of CSE(AI( & ML), RLJIT Page 12


D). PRIORITY:

AIM: To write a c program to simulate the CPU scheduling priority algorithm.

DESCRIPTION:

To calculate the average waiting time in the priority algorithm, sort the burst times
according to their priorities and then calculate the average waiting time of the processes. The
waiting time of each process is obtained by summing up the burst times of all the previous
processes.

ALGORITHM:

Step 1: Start the process.


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

Dept. of CSE(AI( & ML), RLJIT Page 13


SOURCE CODE:

#include<stdio.h>
void main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp;
float wtavg, tatavg;
clrscr();
printf("Enter the number of processes --- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i);
scanf("%d%d",&bt[i], &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];
pri[i]=pri[k];
pri[k]=temp;
}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];

wtavg = wtavg + wt[i];


tatavg = tatavg + tat[i];
}

Dept. of CSE(AI( & ML), RLJIT Page 14


printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURN
AROUND TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n);
printf("\nAverage Turnaround Time is --- %f",tatavg/n);
getch();
}

Dept. of CSE(AI( & ML), RLJIT Page 15


PROGRAM NO 3

AIM: To Write a C program to simulate producer-consumer problem using semaphores.

DESCRIPTION

Producer consumer problem is a synchronization problem. There is a fixed size buffer


where the producer produces items and that is consumed by a consumer process. One
solution to the producer- consumer problem uses shared memory. To allow producer and
consumer processes to run concurrently, there must be available a buffer of items that can
be filled by the producer and emptied by the consumer. This buffer will reside in a region of
memory that is shared by the producer and consumer processes. The producer and consumer
must be synchronized, so that the consumer does not try to consume an item that has not yet
been produced.

SOURCE CODE:

#include<stdio.h>
void main()
{
int buffer[10], bufsize, in, out, produce, consume, choice=0;
in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf(“\n1. Produce\t 2. Consume \t3. Exit”);
printf(“\nEnter your choice: ”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: if((in+1)%bufsize==out)
printf(“\nBuffer is Full”);
else
{
printf(“\nEnter the value: “);
scanf(“%d”, &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
break;;;

case 2: if(in == out)


printf(“\nBuffer is Empty”);

Dept. of CSE(AI( & ML), RLJIT Page 16


else
{
consume = buffer[out];
printf(“\nThe consumed value is %d”, consume);
out = (out+1)%bufsize;
}
break;
}
}
}

Dept. of CSE(AI( & ML), RLJIT Page 17


PROGRAM NO 4

AIM: To Write a C program which demonstrates inter process communication between a


reader process and a writer process. Use mkfifo, open, read, write and also API’s in your
program.

DESCRIPTION:

Producer consumer problem is a synchronization problem. There is a fixed size buffer


where the producer produces items and that is consumed by a consumer process. One
solution to the producer- consumer problem uses shared memory. To allow producer and
consumer processes to run concurrently, there must be available a buffer of items that can
be filled by the producer and emptied by the consumer. This buffer will reside in a region of
memory that is shared by the producer and consumer processes. The producer and consumer
must be synchronized, so that the consumer does not try to consume an item that has not yet
been produced.

SOURCE CODE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_NAME "myfifo" // Name of the FIFO (named pipe)

int main()
{
int fd; // File descriptor for the FIFO

// Create a FIFO (named pipe)


if (mkfifo(FIFO_NAME, 0666) == -1)
{
perror("mkfifo");

Dept. of CSE(AI( & ML), RLJIT Page 18


exit(EXIT_FAILURE);
}

// Writer Process
if (fork() == 0)
{
char message[] = "Hello, reader!"; // Message to be written

// Open the FIFO for writing


fd = open(FIFO_NAME, O_WRONLY);

if (fd == -1)
{
perror("open");
exit(EXIT_FAILURE);
}

// Write the message to the FIFO


if (write(fd, message, sizeof(message)) == -1)
{
perror("write");
exit(EXIT_FAILURE);
}

// Close the FIFO


close(fd);
exit(EXIT_SUCCESS);
}
else
{
// Reader Process

Dept. of CSE(AI( & ML), RLJIT Page 19


char buffer[100]; // Buffer to read the message

// Open the FIFO for reading


fd = open(FIFO_NAME, O_RDONLY);
if (fd == -1)
{
perror("open");
exit(EXIT_FAILURE);
}

// Read the message from the FIFO


ssize_t bytesRead = read(fd, buffer, sizeof(buffer));
if (bytesRead == -1)
{
perror("read");
exit(EXIT_FAILURE);
}

// Null-terminate the received message


buffer[bytesRead] = '\0';

// Display the received message


printf("Received message: %s\n", buffer);

// Close the FIFO


close(fd);

// Remove the FIFO (named pipe)


unlink(FIFO_NAME);

exit(EXIT_SUCCESS);
}
return 0;
}
Dept. of CSE(AI( & ML), RLJIT Page 20
Dept. of CSE(AI( & ML), RLJIT Page 21
PROGRAM NO 5

MEMORY ALLOCATION TECHNIQUES

AIM: To Write a C program to simulate the following contiguous memory allocation


techniques
a) Worst-fit. b) Best-fit. c) First-fit.
DESCRIPTION

One of the simplest methods for memory allocation is to divide memory into several
fixed-sized partitions. Each partition may contain exactly one process. In this multiple-
partition method, when a partition is free, a process is selected from the input queue and is
loaded into the free partition. When the process terminates, the partition becomes available
for another process. The operating system keeps a table indicating which parts of memory
are available and which are occupied. Finally, when a process arrives and needs memory, a
memory section large enough for this process is provided. When it is time to load or swap a
process into main memory, and if there is more than one free block of memory of sufficient
size, then the operating system must decide which free block to allocate. Best-fit strategy
chooses the block that is closest in size to the request. First-fit chooses the first available
block that is large enough. Worst-fit chooses the largest available block.

SOURCE CODE:

WORST-FIT

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,t emp;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme – First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);

Dept. of CSE(AI( & ML), RLJIT Page 22


}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j; break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

Dept. of CSE(AI( & ML), RLJIT Page 23


BEST-FIT

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
clrscr();
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
printf("Block %d:",i);
scanf("%d",&b[i]);
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}

for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
if(lowest>temp)
{
ff[i]=j; lowest=temp;
}
}
}
frag[i]=lowest;
Dept. of CSE(AI( & ML), RLJIT Page 24
bf[ff[i]]=1;
lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock Size\tFragment");
for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

FIRST-FIT

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highes t=0;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - Worst Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);

}
for(i=1;i<=nf;i++)

Dept. of CSE(AI( & ML), RLJIT Page 25


{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i];
if(temp>=0)
if(highest<temp)
{
}
}

frag[i]=highest;
bf[ff[i]]=1;
highest=0;
}
ff[i]=j;
highest=temp;
}
printf("\nFile_no:\tFile_size:\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

Dept. of CSE(AI( & ML), RLJIT Page 26


PROGRAM.NO 6

DEAD LOCK AVOIDANCE

AIM: To Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)

DESCRIPTION:

Deadlock is a situation where in two or more competing actions are waiting f or


the other to finish, and thus neither ever does. When a new process enters a system, it
must declare the maximum number of instances of each resource type it needed. This
number may exceed the total number of resources in the system. When the user request
a set of resources, the system must determine whether the allocation of each resources
will leave the system in safe state. If it will the resources are allocation; otherwise the
process must wait until some other process release the resources.

Data structures

n-umber of process, m-number of resource types.


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

Safety Algorithm

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
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;
Dept. of CSE(AI( & ML), RLJIT Page 27
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 its 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.
11. End

SOURCE CODE :

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int alloc[10][10],max[10][10];
int avail[10],work[10],total[10];
int i,j,k,n,need[10][10];
int m;
int count=0,c=0;
char finish[10];
clrscr();
printf("Enter the no. of processes and resources:");
scanf("%d%d",&n,&m);
for(i=0;i<=n;i++)
finish[i]='n';
printf("Enter the claim matrix:\n");

for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&max[i][j]);
Dept. of CSE(AI( & ML), RLJIT Page 28
printf("Enter the allocation matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&alloc[i][j]);
printf("Resource vector:");
for(i=0;i<m;i++)
scanf("%d",&total[i]);
for(i=0;i<m;i++)
avail[i]=0;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
avail[j]+=alloc[i][j];
for(i=0;i<m;i++)
work[i]=avail[i];
for(j=0;j<m;j++)
work[j]=total[j]-work[j];
for(i=0;i<n;i++)
for(j=0;j<m;j++)
need[i][j]=max[i][j]-alloc[i][j];
A: for(i=0;i<n;i++)
{
c=0;
for(j=0;j<m;j++) if((need[i][j]<=work[j])&&(finish[i]=='n'))
c++;
if(c==m)
{
printf("All the resources can be allocated to Process %d", i+1);
printf("\n\nAvailable resources are:");
for(k=0;k<m;k++)
{
work[k]+=alloc[i][k];
printf("%4d",work[k]);
}
printf("\n");
finish[i]='y';
printf("\nProcess %d executed?:%c \n",i+1,finish[i]);
count++;
}
}
if(count!=n)
goto A;
Dept. of CSE(AI( & ML), RLJIT Page 29
else
printf("\n System is in safe mode");
printf("\n The given state is safe state");
getch();
}

PROGRAM NO.7

PAGE REPLACEMENT ALGORITHMS

AIM: To implement FIFO page replacement technique.


a) FIFO b) LRU

DESCRIPTION:
Page replacement algorithms are an important part of virtual memory management and it helps
the OS to decide which memory page can be moved out making space for the currently needed
page. However, the ultimate objective of all page replacement algorithms is to reduce the
number of page faults.
FIFO-This is the simplest page replacement algorithm. In this algorithm, the operating system
keeps track of all pages in the memory in a queue, the oldest page is in the front of the queue.
When a page needs to be replaced page in the front of the queue is selected for removal.

LRU-In this algorithm page will be replaced which is least recently used

OPTIMAL- In this algorithm, pages are replaced which would not be used for the longest
duration of time in the future. This algorithm will give us less page fault when compared to
other page replacement algorithms.

ALGORITHM:

1. Start the process.


2. Read number of pages n.
3. Read number of pages no.
4. Read page numbers into an array a[i].
5. Initialize avail[i]=0 .to check page hit.
6. Replace the page with circular queue, while re-placing check page availability in
the frame Place avail[i]=1 if page is placed in theframe Count page faults.
Dept. of CSE(AI( & ML), RLJIT Page 30
7. Print the results.
8. Stop the process.

Dept. of CSE(AI( & ML), RLJIT Page 31


A) FIRST IN FIRST OUT

SOURCE CODE :

#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
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)

Dept. of CSE(AI( & ML), RLJIT Page 32


{
fr[top]=page[j];
top++;
pf++; if(top>=frsize) top=0;
}
display();
}
printf("Number of page faults : %d ",pf+frsize);
getch();
}
void display()
{
int i;
printf("\n");
for(i=0;i<3;i++)
printf("%d\t",fr[i]);
}

Dept. of CSE(AI( & ML), RLJIT Page 33


B) LEAST RECENTLY USED

AIM: To implement LRU page replacement technique.

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.

SOURCE CODE :

#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
int index,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;
}
Dept. of CSE(AI( & ML), RLJIT Page 34
}
if(flag1==0)
{
for(i=0;i<3;i++)
{
if(fr[i]==-1)
{
fr[i]=p[j];
flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<3;i++)
fs[i]=0;
for(k=j-1,l=1;l<=frsize-1;l++,k--)
{
for(i=0;i<3;i++)
{
if(fr[i]==p[k]) fs[i]=1;
}
}
for(i=0;i<3;i++)
{
if(fs[i]==0)
index=i;
}
fr[index]=p[j];
pf++;
}
display();
}
printf("\n no of page faults :%d",pf+frsize);
getch();
}

Dept. of CSE(AI( & ML), RLJIT Page 35


void display()
{
int i; printf("\n");
for(i=0;i<3;i++)
printf("\t%d",fr[i]);
}

Dept. of CSE(AI( & ML), RLJIT Page 36


PROGRAM NO.8

FILE ORGANIZATION TECHNIQUES

A) SINGLE LEVEL DIRECTORY:

AIM: Program to simulate Single level directory file organization technique.

DESCRIPTION:

The directory structure is the organization of files into a hierarchy of folders. In a single-
level directory system, all the files are placed in one directory. There is a root directory
which has all files. It has a simple architecture and there are no sub directories. Advantage
of single level directory system is that it is easy to find a file in the directory.

SOURCE CODE :

#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir;

void main()
{
int i,ch;
char f[30];
clrscr();
dir.fcnt = 0;
printf("\nEnter name of directory --");
scanf("%s", dir.dname);
while(1)
{
printf("\n\n1. Create File\t2. Delete File\t3. Search File \n 4. Display Files\t
5.Exit\nEnter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the name of the file -- ");
scanf("%s",dir.fname[dir.fcnt]);
dir.fcnt++;
break;

Dept. of CSE(AI( & ML), RLJIT Page 37


case 2: printf("\nEnter the name of the file -- ");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is deleted ",f);
strcpy(dir.fname[i],dir.fname[dir.fcnt-1]);
break;
}
}
if(i==dir.fcnt)
printf("File %s not found",f);
else
dir.fcnt--;
break;

case 3: printf("\nEnter the name of the file -- ");


scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is found ", f);
break;
}
}
if(i==dir.fcnt)
printf("File %s not found",f);
break;

case 4: if(dir.fcnt==0)
printf("\nDirectory Empty");
else
{
printf("\nThe Files are -- ");
for(i=0;i<dir.fcnt;i++)
printf("\t%s",dir.fname[i]);
}
break;

Dept. of CSE(AI( & ML), RLJIT Page 38


default: exit(0);
}

}
getch();
}

Dept. of CSE(AI( & ML), RLJIT Page 39


B) TWO LEVEL DIRECTORY

AIM: Program to simulate two level file organization technique

DESCRIPTION:

In the two-level directory system, each user has own user file directory (UFD). The
system maintains a master block that has one entry for each user. This master block contains
the addresses of the directory of the users. When a user job starts or a user logs in, the
system's master file directory (MFD) is searched. When a user refers to a particular file, only
his own UFD is searched.

SOURCE CODE :

#include<stdio.h> struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];

void main()
{
int i,ch,dcnt,k;
char f[30], d[30];
clrscr();
dcnt=0;
while(1)
{
printf("\n\n1. Create Directory\t2. Create File\t3. Delete File");
printf("\n4. Search File\t\t5. Display\t6. Exit\t Enter your choice --");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter name of directory -- ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;

Dept., of CSE (AI & ML), RLJIT Page 40


case 2: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",dir[i].fname[dir[i].fcnt]);
dir[i].fcnt++;
printf("File created");
}
if(i==dcnt)
printf("Directory %s not found",d);
break;

case 3: printf("\nEnter name of the directory -- ");


scanf("%s",d);
for(i=0;i<dcnt;i++)
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is deleted ",f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],
dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found",f);
goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
Dept., of CSE (AI & ML), RLJIT Page 41
case 4: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is found ",f);
goto jmp1;
}
}
printf("File %s not found",f); goto jmp1; }
}
}
printf("Directory %s not found",d);
jmp1: break;
case 5: if(dcnt==0)
printf("\nNo Directory's ");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}
break;

default:exit(0);
}
}
getch();

Dept., of CSE (AI & ML), RLJIT Page 42


Page 43
PROGRAM NO.9

FILE ALLOCATION STRATEGIES

A) LINKED:

AIM: To implement linked file allocation technique.

DESCRIPTION:

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

for(i=0;i<n;i++)
{
for(j=0;j<s[i];j++)
{
q=random(100);
if(b[q].flag==0)
b[q].flag=1;
b[q].fno=j;
r[i][j]=q;
if(j>0)
{
}
}
p=r[i][j-1]; b[p].next=q;
}
Step 5: Print the results file no, length ,Blocks allocated.
Step 6: Stop the program

Page 44
SOURCE CODE :

#include<stdio.h>
void main()
{
int f[50],p,i,j,k,a,st,len,n,c;
clrscr();
for(i=0;i<50;i++)
f[i]=0;
printf("Enter how many blocks that are already allocated"); scanf("%d",&p);
printf("\nEnter the blocks no.s that are already allocated");
for(i=0;i<p;i++)
{
scanf("%d",&a);
f[a]=1;
}
X:printf("Enter the starting index block & length");
scanf("%d%d",&st,&len);
k=len;
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n %d->file is already allocated",j);
k++;
}
}
printf("\n If u want to enter one more file? (yes-1/no-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
exit();
getch( );
}

Page 45
PROGRAM NO 10

AIM: To Write a C program to simulate disk scheduling algorithms


A) . SCAN

DESCRIPTION:

One of the responsibilities of the operating system is to use the hardware efficiently.
For the disk drives, meeting this responsibility entails having fast access time and large disk
bandwidth. Both the access time and the bandwidth can be improved by managing the order
in which disk I/O requests are serviced which is called as disk scheduling. The simplest
form of disk scheduling is, of course, the first-come, first-served (FCFS) algorithm. This
algorithm is intrinsically fair, but it generally does not provide the fastest service. In the
SCAN algorithm, the disk arm starts at one end, and moves towards the other end, servicing
requests as it reaches each cylinder, until it gets to the other end of the disk. At the other end,
the direction of head movement is reversed, and servicing continues. The head continuously
scans back and forth across the disk. C-SCAN is a variant of SCAN designed to provide a
more uniform wait time. Like SCAN, C-SCAN moves the head from one end of the disk to
the other, servicing requests along the way. When the head reaches the other end, however,
it immediately returns to the beginning of the disk without servicing any requests on the
return trip.

SCAN DISK SCHEDULING ALGORITHM


#include<stdio.h>
void main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;
clrscr();
printf("enter the no of tracks to be traveresed");
scanf("%d'",&n);
printf("enter the position of head");
scanf("%d",&h);
t[0]=0;
t[1]=h;
printf("enter the tracks");
for(i=2;i<n+2;i++)
scanf("%d",&t[i]);

for(i=0;i<n+2;i++)
Page 46
{
for(j=0;j<(n+2)-i-1;j++)
{
if(t[j]>t[j+1])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}
}
}
for(i=0;i<n+2;i++)
if(t[i]==h)
j=i;k=i;
p=0;
while(t[j]!=0)
{
atr[p]=t[j];
j--; p++;
}
atr[p]=t[j];
for(p=k+1;p<n+2;p++,k++)
atr[p]=t[k+1];
for(j=0;j<n+1;j++)
{
if(atr[j]>atr[j+1])
d[j]=atr[j]-atr[j+1];
else
d[j]=atr[j+1]-atr[j];
sum+=d[j];
}
printf("\nAverage header movements:%f",(float)sum/n);
getch();

Page 47

You might also like