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

OS LAB RECORD

The document is a record for the Operating System Laboratory course at Hindusthan Institute of Technology, detailing various experiments and exercises related to Linux and UNIX commands. It includes instructions for installing Ubuntu, basic UNIX commands, and programming simulations of UNIX commands like cp and ls. The document serves as a practical guide for students to learn and practice operating system concepts.

Uploaded by

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

OS LAB RECORD

The document is a record for the Operating System Laboratory course at Hindusthan Institute of Technology, detailing various experiments and exercises related to Linux and UNIX commands. It includes instructions for installing Ubuntu, basic UNIX commands, and programming simulations of UNIX commands like cp and ls. The document serves as a practical guide for students to learn and practice operating system concepts.

Uploaded by

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

HINDUSTHAN

INSTITUTE OF TECHNOLOGY

COIMBATORE 641 032

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Register Number -----------------------------------------


-

Name …………………………………………………

Class/Sec …………………………………………………
HINDUSTHAN
INSTITUTE OF TECHNOLOGY

COIMBATORE 641 032

This is to Certified that this is the bonafide record of work done


by……………………………………………………………………………in the
22CS405L – OPERATING SYSTEM LABORATORY of this B.E COMPUTER

SCIENCE AND ENGINEERING for the IV Semester during the year 2025.

Place:

Date:

Staff Incharge Head of the Department

UNIVERSITY REGISTER NUMBER ……………………………………………


Submitted for the Autonomous End Semester practical Examination conducted on

……………………………….

Internal Examiner External Examiner


CONTENTS
S.No Date Experiment Page No Marks Sign

10
Ex.No:1 Installation of Operating System, install any
Guest Operating System Linux using VMware

Aim:
To install the Ubuntu and practice linux commands
To Install Ubuntu Linux – Complete Step by Step
Now again select free space from the table and click add option. Now select size to be
around twice the size of your ram that is around 1000 mb if your ram size is 512mb and
select use as swap area and clickok.
Step 6 : Click Install now button and then the wizardwill ask you location.
Select your location and click forward.

\
RESULT:

Thus, the result for the program to install the Ubuntu and practice linux
Commands was verified and executed successfully.
Ex.No:2.a BASICS OF UNIX COMMANDS
INTRODUCTION TO UNIX

AIM:
To study about the basics of UNIX

UNIX:
 It is a multi-user operating system. Developed at AT & T Bell
Industries, USA in 1969.
 Ken Thomson along with Dennis Ritchie developed it from MULTICS
(Multiplexed Information and Computing Service) OS.
 By1980, UNIX had been completely rewritten using C language.

LINUX:
It is similar to UNIX, which is created by Linus Torualds. All UNIX
commands works in Linux. Linux is a open source software. The main feature of
Linux is coexisting with other OS such as windows and UNIX.

STRUCTURE OF A LINUX SYSTEM:


It consists of three parts.
a)UNIX kernel
b) Shells
c) Tools and Applications

UNIX KERNEL:
 Kernel is the core of the UNIX OS. It controls all tasks, schedule all
Processes and carries out all the functions of OS.
 Decides when one programs tops and another starts.
SHELL:
Shell is the command interpreter in the UNIX OS. It accepts command from
the user and analyses and interprets them.
Ex.No:2.b BASICS OF UNIX COMMANDS

BASIC UNIX COMMANDS

AIM:
To study of Basic UNIX Commands and various UNIX editors such as vi,
ed, ex and EMACS.

CONTENT:
Note: Syn->Syntax

a) date –used to check the date and time


Syn:$date
Format Purpose Example Result

+%m To display only month $date+%m 06

+%h To display month name $date+%h June

+%d To display day of month $date+%d O1

+%y To display last two digits of years $date+%y 09

+%H To display hours $date+%H 10

+%M To display minutes $date+%M 45


+%S To display seconds $date+%S 55

b) cal –used to display the calendar


Syn:$cal 3 2025
c)echo –used to print the message on the screen.
Syn:$echo “text”

[hitcse@hit ~]$ echo "hello world"


hello world

d) ls –used to list the files. Your files are kept in a directory.


Syn:$lsls–s All files (include files with prefix)
ls–l Lodetai (provide file statistics)
ls–t Order by creation time
ls– u Sort by access time (or show when last accessed together with –l)
ls–s Order by size
ls–r Reverse order
ls–f Mark directories with /,executable with* , symbolic links with @, local sockets
with=, named pipes(FIFOs)
ls–s Show file size
ls– h“ Human Readable”, show file size in Kilo Bytes & Mega Bytes (h can be used
together with –l or)
ls[a-m]*List all the files whose name begin with alphabets From „a‟ to „m‟ ls[a]*List
all the files whose name begins with „a‟ or „A‟
Eg:$ls>my list Output of „ls‟ command is stored to disk file named „my list‟ .

[hitcse@hit ~]$ ls
{ komali.c
} Last
10.c leap_year.sh
1.a leapyear.sh
2a ls_unix
4a ls_unix.c

e)lp –used to take printouts


Syn:$lp filename

[hitcse@hit ~]$ lp fork.c


lp: Error - no default destination available.

f)man –used to provide manual help on every UNIX commands.


Syn:$man unix command
$man cat
[hitcse@hit ~]$ man cat
CAT(1) User Commands CAT(1)

NAME
cat - concatenate files and print on
the standard output

SYNOPSIS
cat [OPTION] [FILE]...

DESCRIPTION
Concatenate FILE(s), or standard
input, to standard output.

-A, --show-all
equivalent to -vET

-b, --number-nonblank
number nonblank output lines

-e equivalent to -vE

-E, --show-ends
display $ at end of each line

-n, --number

g)who & whoami –it displays data about all users who have logged into the system
currently. The next command displays about current user only.
Syn:$who$whoami

[hitcse@hit ~]$ who


hitit124 pts/1 2025-04-01 01:27 (172.16.1.57)
hitit116 pts/2 2025-04-01 01:30 (172.16.1.29)
[hitcse@hit ~]$ whoami
Hitcse

h) uptime –tells you how long the computer has been running since its last reboot or
power-off.
Syn:$uptime

[hitcse@hit ~]$ uptime


02:18:04 up 48 days, 23:12, 25 users, load average: 0.08, 0.03, 0.01
i)uname –it displays the system information such as hardware platform, system name
and processor, OS type.
Syn:$uname–a

[hitcse@hit ~]$ uname


Linux

j) hostname –displays and set system host name


Syn:$ hostname

[hitcse@hit ~]$ hostname


hit.com

k) bc –stands for „best calculator‟


$bc $ bc $ bc $ bc
10/2*3 scale =1 ibase=2 sqrt(196)
15 2.25+1 obase=16 14 quit
3.35 11010011
quit 89275
1010
Ā
Quit

$bc $ bc-l
for(i=1;i<3;i=i+1)I scale=2
1 s(3.14)
2 0
3 quit

[hitcse@hit ~]$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
sqrt(196)
14
FILE MANIPULATION COMMANDS

a)cat–this create, view and concatenate files.


Creation: Syn:$cat>filename
Viewing: Syn:$cat filename
Add text to an existing file: Syn:$cat>>filename
Concatenate: Syn:$catfile1file2>file3
$catfile1file2>>file3 (no over writing of file3)

[hitcse@hit ~]$ cat>os.c

[hitcse@hit ~]$ cat example.txt


cat: example.txt: No such file or directory
[hitcse@hit ~]$ cat ex.txt
hello world.
hello again.

b)grep–used to search a particular word or pattern related to that word from the file.
Syn:$grep search word filename
Eg:$grep anu student

[hitcse@hit ~]$ grep hello ex.txt


hello world.
hello again.

c)rm–deletes a file from the file system


Syn:$rm filename

[hitcse@hit ~]$ rm prge.c

d)touch–used to create a blank file.


Syn:$touch file names

[hitcse@hit ~]$ touch fork.c

e)cp–copies the files or directories


Syn:$cpsource file destination file
Eg:$cp student stud
[hitcse@hit ~]$ cp ex.txt os.c

f)mv–to rename the file or directory


syn:$mv old file new file
Eg:$mv–i student student list(-i prompt when overwrite)

[hitcse@hit ~]$ mv ex.txt example.txt

g)cut–it cuts or pickup a given number of character or fields of the file.


Syn:$cut<option><filename>
Eg: $cut –c filename
$cut–c1-10emp
$cut–f 3,6emp
$ cut –f 3-6 emp
-c cutting columns
-f cutting fields

[hitcse@hit ~]$ cut -c5 example.txt


o
o
a
o
o

h)head–displays10 lines from the head(top)of a given file


Syn:$head filename
Eg:$head student
Syn:$head-2student

[hitcse@hit ~]$ head example.txt


hello world.
hello again.
operating systems.
c programming.
welcome you all

i)tail–displays last 10 lines of the file


Syn:$tail filename
Eg:$tail student
To display the bottom two lines;
Syn:$ tail -2 student

[hitcse@hit ~]$
[hitcse@hit ~]$ tail fork.c
pid1 = getpid(); // Get the parent process ID
printf("\nThe parent process ID is %d\n", pid1);
}
else
{
pid2 = getpid(); // Get the child process ID
printf("\nThe child process ID is %d\n", pid2);
}
}

j)chmod–used to change the permissions of a file or directory.


Syn:$ch mod category operation permission file
Where, Category–is the user type
Operation–is used to assign or remove permission
Permission–is the type of permission
File–are used to assign or remove permission all.
Examples:
$chmodu-wx student
Removes write and execute permission for users
$ch modu+rw,g+rwstudent
Assigns read and write permission for users and groups
$chmodg=rwx student
Assigns absolute permission for groups of all read, write and execute permissions

k)wc–it counts the number of lines, words, character in a specified file(s) with the
options as –l,-w,-c
Category Operation Permission
u– users +assign r– read
g–group -remove w– write
o– others =assign absolutely x-execute
Syn: $wc –l filename
$wc –w filename
$wc–c filename

[hitcse@hit ~]$ wc -w fork.c


90 fork.c
[hitcse@hit ~]$ wc -l fork.c
28 fork.c
[hitcse@hit ~]$ wc -c fork.c
616 fork.c
Ex.No:2.c BASICS OF UNIX COMMANDS

UNIX EDITORS

AIM:
To study of various UNIX editors such as vi, ed, ex and EMACS.

CONCEPT:
Editor is a program that allows user to see a portions a file on the screen and
modify characters and lines by simply typing at the current position. UNIX supports
variety of Editors. They are:
ed ex
vi
EM
ACS
Vi- vi is stands for “visual”.vi is the most important and powerful editor.vi is a full
screen editor that allows user to view and edit entire document at the same time.vi
editor was written in the University of California, at Berkley by Bill Joy, who is one
of the co-founder of Sun Microsystems.

Features of vi:
 It is easy to learn and has more powerful features.
 It works great speed and is case sensitive vi has powerful undo functions
and has3modes:
1. Command mode
2. Insert mode
3. Escape or ex mode
In command mode, no text is displayed on the screen.
In Insert mode, it permits user to edit insert or replace text.
In escape mode, it displays commands at command line.
Moving the cursor with the help of h, l, k, j, I, etc

EMACS Editor
Motion Commands:
M-> Move to end of file
M-< Move to beginning of file
C-v Move forward a screen
M –v Move backward a screen
C –n Move to next line
C-p Move to previous line
C-a Move to the beginning of the line
C-e Move to the end of the line
C-f Move forward a character
C-b Move backward a character
M-f Move forward a word
M-b Move backward a word
Deletion Commands:
DEL delete the previous character
C -d delete the current character
M -DEL delete the previous word
M-d delete the next word
C-x DEL deletes the previous sentence
M-k delete the rest of the current sentence
C-k deletes the rest of the current line
C-xu undo the lasted it change
Search and Replace in EMACS:
y Change the occurrence of the pattern
n Don‟t change the occurrence, but look for the other
q Don‟t change. Leave query replace completely
! Change this occurrence and all others in the file

RESULT:
Thus,the result for the basic unix commands are verified successfully.
Ex.No:2.d C PROGRAMS TO SIMULATE UNIX COMMANDS
LIKE cp,ls,grep

AIM:
To write C programs to simulate UNIX commands like cp, ls, grep.

1.Program for simulation of cp unix commands

ALGORITHM:
STEP1: Start the program
STEP 2:Declare the variables ch, *fp, sc=0
STEP3: Open the file in read mode
STEP 4: Get the character
STEP 5: If ch== “ “ then increment sc value by
one STEP 6: Print no of spaces
STEP 7:Close the file

PROGRAM:

#include<stdio.h>
int main(int argc, char *argv[])
{
FILE *fp;
char ch;
int sc = 0;
// Ensure that a file name is passed as a command line argument
if (argc != 2) {
printf("Usage: %s <filename>\n", argv[0]);
return 1;
}
// Open the file in read mode
fp = fopen(argv[1], "r");
// Check if the file was opened successfully
if (fp == NULL) {
printf("Unable to open the file: %s\n", argv[1]);
return 1;
}

else {
// Read each character from the file
while ((ch = fgetc(fp)) != EOF) {
if (ch == ' ') {
sc++; // Increment space count
}
}

// Print the number of spaces found


printf("Number of spaces: %d\n", sc);
fclose(fp); // Close the file
}

return 0;
}

OUTPUT:
2.PROGRAM FOR SIMULATION OF LS UNIX COMMANDS

ALGORTIHM:

STEP1 : Start the program


STEP2 : Open the directory with directory object dp
STEP3 : Read the directory content and print it.
STEP4: Close the directory.

PROGRAM:

#include<stdio.h>
#include<dirent.h>
#include<stdlib.h>
int main(int argc, char **argv) {
DIR *dp;
struct dirent *link;
if (argc != 2) {
printf("Usage: %s <directory>\n", argv[0]);
return 1;
}
dp = opendir(argv[1]);
if (dp == NULL) {
perror("Cannot open directory");
return 1;
}
printf("\nContents of the directory %s are:\n", argv[1]);
while ((link = readdir(dp)) != NULL)
printf("%s\n", link->d_name);
closedir(dp);
return 0;
}
OUTPUT:
3. PROGRAM FOR SIMULATION OF GREP UNIX
COMMANDS

ALGORITHM:

STEP1: Start the program


STEP2: Declare the variables fline[max], count=0, occurrences=0 and
pointers *fp, *newline.
STEP 3: Open the file in read mode.
STEP4: In while loop check fgets(fline,max,fp)!=NULL
STEP 5: Increment count value.
STEP 6: Check newline=strchr(fline, „\n‟)
STEP 7: print the count,fline value and increment the occurrence value.
STEP 8: Stop the program.

PROGRAM:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 1024
void usage() {
printf("Usage: ./a.out <filename> <word>\n");
}
int main(int argc, char *argv[]) {
FILE *fp;
char fline[MAX];
char *newline;
int count = 0;
int occurrences = 0;
if (argc != 3) {
usage();
exit(1);
}
if (!(fp = fopen(argv[1], "r"))) {
printf("grep: Could not open file: %s\n", argv[1]);
exit(1);
}
while (fgets(fline, MAX, fp) != NULL) {
count++;
if ((newline = strchr(fline, '\n')) != NULL)
*newline = '\0';
if (strstr(fline, argv[2]) != NULL) {
printf("%s: %d %s\n", argv[1], count, fline);
occurrences++;
}
}
fclose(fp);
return 0;
}

OUTPUT:

RESULT:
Thus,the result for the C programs to simulate UNIX commands like cp,ls, grep
has been verified and exexcuted successfully.
Ex.No:2.e SIMPLE SHELL PROGRAMS

AIM:
To write simple shell programs by using conditional, branching and looping
statements.

1.Write a Shell program to check the given number is even or Odd.

ALGORITHM:
SEPT 1: Start the program.
STEP 2: Read the value of n.
STEP 3: Calculate „r=expr $n%2‟.
STEP 4: If the value of r equals 0 then print the number is even
STEP 5: If the value of r not equal to 0 then print the number is odd.

PROGRAM:
echo "Enter the Number"
read n
r=$((n % 2)) # Use $(( )) for arithmetic operations
if [ $r -eq 0 ]; then
echo "$n is an Even number"
else
echo "$n is an Odd number"
fi

OUTPUT:
2.Write a Shell program to check the given year is leap year or not

ALGORITHM:
SEPT 1: Start the program.
STEP 2: Read the value of year.
STEP 3: Calculate „b=expr $y%4‟.
STEP 4: If the value of b equals 0 then print the year is a leap year
STEP 5: If the value of r not equal to 0 then print the year is not a leap year.

PROGRAM:

echo "Enter the year"


read y
if [ $((y % 400)) -eq 0 ]; then
echo "$y is a leap year"
elif [ $((y % 4)) -eq 0 ] && [ $((y % 100)) -ne 0 ]; then
echo "$y is a leap year"
else
echo "$y is not a leap year"
fi

OUTPUT:
3.Write a Shell program to find the factorial of a number

ALGORITHM:
SEPT 1: Start the program.
STEP 2: Read the value of n.
STEP 3: Calculate „i=expr $n-1‟.
STEP 4: If the value of i is greater than 1 then calculate „n=expr $n \* $i‟ and
„i=expr $i – 1‟
STEP 5: Print the factorial of the given number.

PROGRAM:

echo "Enter a Number"


read n
if [ $n -lt 0 ]; then
echo "Factorial is not defined for negative numbers."
exit 1
fi
fact=1
i=$n
while [ $i -gt 1 ]; do
fact=$((fact * i)) # Correct arithmetic syntax
i=$((i - 1))# Decrement i properly
done
echo "The Factorial of the given Number is $fact"

OUTPUT:
4.Write a Shell program to swap the two integers

ALGORITHM:
SEPT 1: Start the program.
STEP 2: Read the value of a,b.
STEP 3: Calculate the swapping of two values by using a temporary
variable temp.
STEP 4: Print the value of a and b.

PROGRAM:
echo "Enter Two Numbers"
read a
read b
# Swapping logic
temp=$a
a=$b
b=$temp
echo "After swapping:"
echo "a = $a, b = $b"

OUTPUT:

RESULT:
Thus,the result for the simple shell programs has been verified and executed.
successfully.
Ex.No:3 Programs using the following System Calls of UNIX
Operating System fork, exec, getpid, exit, wait, close

AIM:
To write C Programs using the following system calls of UNIX operating
system fork, exec, getpid, exit, wait, close, stat, opendir, readdir.

PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEM (fork, getpid,


exit)

ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables pid,pid1,pid2.
STEP 3: Call fork() system call to create process.
STEP 4: If pid==-1, exit.
STEP 5: Ifpid!=-1 , get the process id using getpid().
STEP 6: Print the process id.
STEP 7:Stop the program

PROGRAM:

#include <stdio.h>
#include <unistd.h> // Include the correct header
#include <stdlib.h> // Include this for exit() function
void main()
{
int pid, pid1, pid2;
pid = fork(); // Create a child proces
if (pid == -1)
{
printf("ERROR IN PROCESS CREATION \n"); // If fork fails
exit(1);
}

if (pid != 0)
{
pid1 = getpid(); // Get the parent process ID
printf("\nThe parent process ID is %d\n", pid1);
}
else
{
pid2 = getpid(); // Get the child process ID
printf("\nThe child process ID is %d\n", pid2);
}
}

OUTPUT:

RESULT:
Thus,the result for the program for system calls of unix operating system was
verified and executed successfully.
Ex.No:4(a) CPU SCHEDULING ALGORITHMS

PRIORITY SCHEDULING

AIM:
To write a C program for implementation of Priority scheduling algorithms.

ALGORITHM:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i,j as integer, totwtime and totttime is equal
to zero.
Step 3: Get the value of „n‟ assign p and allocate the memory.
Step 4: Inside the for loop get the value of burst time and
priority.
Step 5: Assign wtime as zero .
Step 6: Check p[i].pri is greater than p[j].pri .
Step 7: Calculate the total of burst time and waiting time and assign as
turnaround time.
Step 8: Stop the program.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct {
int pno;
int pri;
int btime;
int wtime;
} sp;
int main() {
int i, j, n;
int tbm = 0, totwtime = 0, totttime = 0;
sp *p, t;
printf("\nPRIORITY SCHEDULING.\n");
printf("\nEnter the number of processes: ");
scanf("%d", &n);
// Allocate memory for processes
p = (sp*)malloc(n * sizeof(sp));
if (p == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input process details
printf("Enter burst time and priority for each process:\n");
for (i = 0; i < n; i++) {
printf("Process %d: ", i + 1);
scanf("%d %d", &p[i].btime, &p[i].pri);
p[i].pno = i + 1;
p[i].wtime = 0;
}
// Sorting based on priority (Ascending Order: Lower value = Higher priority)
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (p[i].pri > p[j].pri) {
t = p[i];
p[i] = p[j];
p[j] = t;
}
}
}
// Displaying process scheduling
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
totwtime += p[i].wtime = tbm; // Waiting time is total burst time so far
tbm += p[i].btime;
printf("%d\t\t%d\t\t%d\t\t%d\n", p[i].pno, p[i].btime, p[i].wtime, p[i].wtime +
p[i].btime);
}
totttime = tbm; // Total turnaround time
printf("\nTotal waiting time: %d", totwtime);
printf("\nAverage waiting time: %.2f", (float)totwtime / n);
printf("\nTotal turnaround time: %d", totttime);
printf("\nAverage turnaround time: %.2f\n", (float)totttime / n);
// Free allocated memory
free(p);
return 0;
}

OUTPUT:
Ex.NO:4(b) CPU SCHEDULING ALGORITHMS

ROUND ROBIN SCHEDULING

AIM:
To write a C program for implementation of Round Robin
scheduling algorithms.

ALGORITHM:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i,j as integer, totwtime and totttime is equal
to zero.
Step 3: Get the value of „n‟ assign p and allocate the memory.
Step 4: Inside the for loop get the value of burst time and priority and read the
time quantum.
Step 5: Assign wtime as zero.
Step 6: Check p[i].pri is greater than p[j].pri .
Step 7: Calculate the total of burst time and waiting time and assign as
turnaround time.
Step 8: Stop the program.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct rr {
int pno, btime, sbtime, wtime, lst;
} p[10];
int main() {
int pp = -1, ts, flag, count, ptm = 0, i, n, twt = 0, totttime = 0;
printf("\nROUND ROBIN SCHEDULING\n");
printf("Enter number of processes: ");
scanf("%d", &n);
printf("Enter the time slice: ");
scanf("%d", &ts);
printf("Enter the burst times:\n");
for (i = 0; i < n; i++) {
printf("Process %d: ", i + 1);
scanf("%d", &p[i].btime);
p[i].wtime = p[i].lst = 0;
p[i].pno = i + 1;
p[i].sbtime = p[i].btime; // Save original burst time
}
printf("\nScheduling:\n");
do {
flag = 0;
for (i = 0; i < n; i++) {
count = p[i].btime;
if (count > 0) {
flag = 1;
count = (count >= ts) ? ts : count;
printf("Process %d executed from %d to %d\n", p[i].pno, ptm, ptm + count);
ptm += count;
p[i].btime -= count;
if (pp != i) {
pp = i;
p[i].wtime += ptm - p[i].lst - count;
p[i].lst = ptm;
}
}
}
} while (flag);
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++) {
int turnaround_time = p[i].wtime + p[i].sbtime;
twt += p[i].wtime;
totttime += turnaround_time;
printf("%d\t\t%d\t\t%d\t\t%d\n", p[i].pno, p[i].sbtime, p[i].wtime,
turnaround_time);
}
printf("\nTotal Waiting Time: %d", twt);
printf("\nAverage Waiting Time: %.2f", (float)twt / n);
printf("\nTotal Turnaround Time: %d", totttime);
printf("\nAverage Turnaround Time: %.2f\n", (float)totttime / n);
return 0;
}
OUTPUT:
Ex.NO:4(c) CPU SCHEDULING ALGORITHMS

FCFS

AIM:
To write a C program for implementation of FCFS and SJF scheduling
algorithms.

ALGORITHM:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i,j as integer,totwtime and totttime is equal
to zero.
Step 3: Get the value of „n‟ assign pid as I and get the value of
p[i].btime.
Step 4: Assign p[0] wtime as zero and tot time as btime and inside the loop
calculate wait time and turnaround time.
Step 5: Calculate total wait time and total turnaround time by dividing by
total number of process.
Step 6: Print total wait time and total turnaround
time.
Step 7: Stop the program.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct fcfs
{
int pid; // Process ID
int btime; // Burst Time
int wtime; // Waiting Time
int ttime; // Turnaround Time
} p[10];
int main()
{
int i, n;
int totwtime = 0, totttime = 0;
printf("\nFCFS Scheduling...\n");
printf("Enter the number of processes: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
p[i].pid = i + 1; // Assigning process ID
printf("\nEnter burst time of process %d: ", p[i].pid);
scanf("%d", &p[i].btime);
}
// First process waiting time is 0
p[0].wtime = 0;
p[0].ttime = p[0].btime;
totttime += p[0].ttime;
for (i = 1; i < n; i++)
{
p[i].wtime = p[i - 1].wtime + p[i - 1].btime;
p[i].ttime = p[i].wtime + p[i].btime;

totwtime += p[i].wtime;
totttime += p[i].ttime;
}
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++)
{
printf("%d\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].btime, p[i].wtime, p[i].ttime);
}
printf("\nTotal Waiting Time: %d", totwtime );
printf("\nAverage Waiting Time: %.2f", (float)totwtime / n);
printf("\nTotal Turnaround Time: %d", totttime);
printf("\nAverage Turnaround Time: %.2f\n", (float)totttime / n);
return 0;
}
OUTPUT:
Ex.NO:4(d) CPU SCHEDULING ALGORITHMS

SJF SCHEDULING

AIM:
To write a C program for implementation of SJF scheduling algorithms.

ALGORITHM:
Step 1: Inside the structure declare the variables.
Step 2: Declare the variable i,j as integer,totwtime and totttime is equal
to zero.
Step 3: Get the value of „n‟ assign pid as I and get the value of
p[i].btime.
Step 4: Assign p[0] wtime as zero and tot time as btime and inside the loop
calculate wait time and turnaround time.
Step 5: Calculate total wait time and total turnaround time by dividing by
total number of process.
Step 6: Print total wait time and total turnaround
time.
Step 7: Stop the program.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct
{
int pid; // Process ID
int btime; // Burst Time
int wtime; // Waiting Time
} sp;
int main()
{
int i, j, n, tbm = 0, totwtime = 0, totttime = 0;
sp *p, t;
printf("\nSJF Scheduling...\n");
printf("Enter the number of processes: ");
scanf("%d", &n);
p = (sp *)malloc(n * sizeof(sp)); // Allocate memory for n processes
printf("\nEnter the burst times:\n");
for (i = 0; i < n; i++)
{
printf("Process %d: ", i + 1);
scanf("%d", &p[i].btime);
p[i].pid = i + 1;
p[i].wtime = 0;
}
// Sorting the processes based on burst time (SJF)
for (i = 0; i < n - 1; i++)
{
for (j = i + 1; j < n; j++)
{
if (p[i].btime > p[j].btime)
{
t = p[i];
p[i] = p[j];
p[j] = t;
}
}
}
printf("\nProcess Scheduling:\n");
printf("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time\n");
for (i = 0; i < n; i++)
{
p[i].wtime = tbm; // Waiting time = sum of previous burst times
tbm += p[i].btime;
totwtime += p[i].wtime;
totttime += tbm;
printf("%d\t\t%d\t\t%d\t\t%d\n", p[i].pid, p[i].btime, p[i].wtime, tbm);
}
printf("\nTotal Waiting Time: %d", totwtime);
printf("\nAverage Waiting Time: %.2f", (float)totwtime / n);
printf("\nTotal Turnaround Time: %d", totttime);
printf("\nAverage Turnaround Time: %.2f\n", (float)totttime / n);
free(p); // Free allocated memory
return 0;
}
OUTPUT:

RESULT:
Thus, the result for the CPU scheduling has been verified and executed
Successfully.
Ex.NO:5 ALGORITHM FOR DEADLOCK DETECTION

AIM:
To write a C program to implement algorithm for deadlock detection.
ALGORITHM:
Step-1: Start the program.
Step-2: Declare the memory for the process.
Step-3: Read the number of process, resources, allocation matrix and
available matrix.
Step-4: Compare each and every process using the banker’s algorithm.
Step-5: If the process is in safestate then it is a not a deadlock process
otherwise it is a deadlock process.
Step-6: produce the result of state of process.
Step-7: Stop the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n, r;
void input();
void show();
void cal();
int main() {
printf("********** Deadlock Detection Algorithm ************\n");
input();
show();
cal();
return 0;
}
void input() {
int i, j;
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the number of resource instances: ");
scanf("%d", &r);

printf("Enter the Max Matrix:\n");


for (i = 0; i < n; i++) {
for (j = 0; j < r; j++) {
scanf("%d", &max[i][j]);
}
}
printf("Enter the Allocation Matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < r; j++) {
scanf("%d", &alloc[i][j]);
}
}
printf("Enter the Available Resources:\n");
for (j = 0; j < r; j++) {
scanf("%d", &avail[j]);
}
}
void show() {
int i, j;
printf("\nProcess\t Allocation\t Max\t Available\n");
for (i = 0; i < n; i++) {
printf("P%d\t ", i + 1);
for (j = 0; j < r; j++) {
printf("%d ", alloc[i][j]);
}
printf("\t");
for (j = 0; j < r; j++) {
printf("%d ", max[i][j]);
}
printf("\t");
if (i == 0) {
for (j = 0; j < r; j++) {
printf("%d ", avail[j]);
}
}
printf("\n");
}
}

void cal() {
int finish[100], dead[100], flag = 1, i, j, k;
for (i = 0; i < n; i++) {
finish[i] = 0;
}

// Calculate the Need matrix


for (i = 0; i < n; i++) {
for (j = 0; j < r; j++) {
need[i][j] = max[i][j] - alloc[i][j];
}
}

while (flag) {
flag = 0;
for (i = 0; i < n; i++) {
int can_allocate = 1;
for (j = 0; j < r; j++) {
if (need[i][j] > avail[j]) {
can_allocate = 0;
break;
}
}
if (can_allocate && finish[i] == 0) {
for (k = 0; k < r; k++) {
avail[k] += alloc[i][k];
}
finish[i] = 1;
flag = 1;
}
}
}
int deadlock = 0;
printf("\n");
for (i = 0; i < n; i++) {
if (finish[i] == 0) {
dead[deadlock++] = i;
}
}

if (deadlock > 0) {
printf("System is in Deadlock. The deadlocked processes are:\n");
for (i = 0; i < deadlock; i++) {
printf("P%d\t", dead[i]);
}
printf("\n");
} else {
printf("No Deadlock Occurred\n");
}
}

OUTPUT:

RESULT:
Thus, the result for the algorithm for deadlock detection has been verified and
executed successfully.
Ex.NO:6 BANKERS ALGORITHM FOR DEADLOCK
AVOIDANCE

AIM:
To write a C program to implement banker’s algorithm for deadlock avoidance.

ALGORITHM:

Step-1: Start the program.


Step-2: Declare the memory for the process.
Step-3: Read the number of process, resources, allocation matrix and
available matrix.
Step-4: Compare each and every process using the banker‟s algorithm.
Step-5: If the process is in safe state then it is a not a deadlock process
otherwise it is a deadlock process
Step-6: produce the result of state of Process.
Step-7: Stop the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n, r;
void input();
void show();
void cal();
int main()
{
printf("********** Banker's Algorithm ************\n");
input();
show();
cal();
return 0;
}
void input()
{
int i, j;
printf("Enter the number of Processes: ");
scanf("%d", &n);
printf("Enter the number of Resource Instances: ");
scanf("%d", &r);

printf("Enter the Max Matrix:\n");


for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
scanf("%d", &max[i][j]);
}
}
printf("Enter the Allocation Matrix:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
scanf("%d", &alloc[i][j]);
}
}

printf("Enter the Available Resources:\n");


for (j = 0; j < r; j++)
{
scanf("%d", &avail[j]);
}
}
void show()
{
int i, j;
printf("\nProcess\t Allocation\t Max\t Available\n");
for (i = 0; i < n; i++)
{
printf("P%d\t ", i + 1);
for (j = 0; j < r; j++)
{
printf("%d ", alloc[i][j]);
}
printf("\t");
for (j = 0; j < r; j++)
{
printf("%d ", max[i][j]);
}
printf("\t");
if (i == 0)
{
for (j = 0; j < r; j++)
printf("%d ", avail[j]);
}
printf("\n");
}
}
void cal()
{
int finish[100] = {0}, safeSeq[100], flag = 1, i, j, k, c1 = 0;

// Calculate the Need matrix


for (i = 0; i < n; i++)
{
for (j = 0; j < r; j++)
{
need[i][j] = max[i][j] - alloc[i][j];
}
}
printf("\n");
while (flag)
{
flag = 0;
for (i = 0; i < n; i++)
{
int canAllocate = 1;
for (j = 0; j < r; j++)
{
if (need[i][j] > avail[j])
{
canAllocate = 0;
break;
}
}
if (canAllocate && finish[i] == 0)
{
for (k = 0; k < r; k++)
{
avail[k] += alloc[i][k];
}
finish[i] = 1;
safeSeq[c1++] = i;
flag = 1;
}
}
}

if (c1 == n)
{
printf("\nThe system is in a safe state. Safe sequence: ");
for (i = 0; i < n; i++)
{
printf("P%d ", safeSeq[i]);
}
printf("\n");
}
else
{
printf("\nProcesses are in deadlock\n");
printf("System is in an unsafe state\n");
}
}
OUTPUT:

RESULT:
Thus, the result for the banker’s algorithm for deadlock avoidance has been
verified and executed successfully.
Ex.NO:7 PAGING TECHNIQUE OF MEMORY
MANAGEMENT

AIM:
To write a c program to implement Paging technique for memory management.

ALGORITHM:
Step 1: Start the process
Step 2: Declare page number, page table, frame number and process size.
Step 3: Read the process size, total number of pages
Step 4: Read the relative address
Step 5: Calculate the physical Address.
Step 6: Display the address
Step 7: Stop the process.

PROGRAM:

#include <stdio.h>
int main() {
int pageSize, numPages, numFrames, logicalAddr, pageNumber, offset;
int pageTable[100];
int i; // Declare loop variable here

printf("Enter the number of pages: ");


scanf("%d", &numPages);

printf("Enter the page size (in bytes): ");


scanf("%d", &pageSize);

printf("Enter the number of frames in memory: ");


scanf("%d", &numFrames);

// Initializing Page Table


printf("\nEnter the frame number for each page (-1 if not loaded in memory):\n");
for (i = 0; i < numPages; i++) { // Use the previously declared i
printf("Page %d -> Frame: ", i);
scanf("%d", &pageTable[i]);
}
// Logical to Physical Address Translation
printf("\nEnter a logical address (page number and offset): ");
scanf("%d %d", &pageNumber, &offset);

// Check if the page is loaded in memory


if (pageNumber >= numPages || pageTable[pageNumber] == -1) {
printf("Error: Page not found in memory (Page Fault!)\n");
}
else if (offset >= pageSize) {
printf("Error: Offset exceeds page size!\n");
}
else {
int frameNumber = pageTable[pageNumber];
int physicalAddr = (frameNumber * pageSize) + offset;
printf("Physical Address: %d\n", physicalAddr);
}

return 0;
}
OUTPUT:

RESULT:
Thus,the result for the paging technique of memory management has been
verified and executed successfully.
Ex.NO:8(a) MEMORY ALLOCATION METHODS FOR
FIXED PARTITION

FIRST FIT

AIM:
To write a C program for implementation memory allocation methods for
fixed partition using first fit.

ALGORITHM:
Step 1:Define the max as 25.
Step 2: Declare the variable frag[max],b[max],f[max],i,j,nb,nf,temp,
highest=0, bf[max],ff[max].
Step 3: Get the number of blocks,files,size of the blocks using for loop.
Step 4: In for loop check bf[j]!=1, if so temp=b[j]-f[i]
Step 5: Check highest<temp,if so assign ff[i]=j,highest=temp Step 6: Assign
frag[i]=highest, bf[ff[i]]=1,highest=0
Step 7: Repeat step 4 to step 6.
Step 8: Print file no,size,block no,size and fragment.
Step 9: Stop the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
#define MAX 25

void main()
{
int frag[MAX], b[MAX], f[MAX], i, j, nb, nf, temp;
static int bf[MAX], ff[MAX];

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 = 0; i < nb; i++)
{
printf("Block %d: ", i + 1);
scanf("%d", &b[i]);
bf[i] = 0; // Initialize block allocation status
}

printf("Enter the size of the files:\n");


for (i = 0; i < nf; i++)
{
printf("File %d: ", i + 1);
scanf("%d", &f[i]);
ff[i] = -1; // Initialize file allocation status
}

for (i = 0; i < nf; i++)


{
for (j = 0; j < nb; j++)
{
if (bf[j] == 0 && b[j] >= f[i]) // Block not allocated and big enough
{
ff[i] = j;
temp = b[j] - f[i];
frag[i] = temp;
bf[j] = 1; // Mark block as allocated
break;
}
}
}

printf("\nFile_no:\tFile_size:\tBlock_no:\tBlock_size:\tFragment");
for (i = 0; i < nf; i++)
{
if (ff[i] != -1)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", i + 1, f[i], ff[i] + 1, b[ff[i]], frag[i]);
else
printf("\n%d\t\t%d\t\tNot Allocated", i + 1, f[i]);
}
}
OUTPUT:
Ex.NO:8(b) MEMORY ALLOCATION METHODS FOR
FIXED PARTITION

WORST FIT

AIM:
To write a C program for implementation memory allocation methods for
fixed partition using worst fit.

ALGORITHM:
Step 1:Define the max as 25.
Step 2: Declare the variable frag[max],b[max],f[max],i,j,nb,nf,temp,
highest=0, bf[max],ff[max].
Step 3: Get the number of blocks,files,size of the blocks using for loop.
Step 4: In for loop check bf[j]!=1, if so temp=b[j]-f[i]
Step 5: Check temp>=0,if so assign ff[i]=j break the for loop.
Step 6: Assign frag[i]=temp,bf[ff[i]]=1;
Step 7: Repeat step 4 to step 6.
Step 8: Print file no,size,block no,size and fragment.
Step 9: Stop the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
#define MAX 25
void main()
{
int frag[MAX], b[MAX], f[MAX], i, j, nb, nf, temp, highest;
static int bf[MAX], ff[MAX];
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 = 0; i < nb; i++)
{
printf("Block %d: ", i + 1);
scanf("%d", &b[i]);
bf[i] = 0; // Initialize block allocation status
}
printf("Enter the size of the files:\n");
for (i = 0; i < nf; i++)
{
printf("File %d: ", i + 1);
scanf("%d", &f[i]);
ff[i] = -1; // Initialize file allocation status
}
for (i = 0; i < nf; i++)
{
highest = -1;
for (j = 0; j < nb; j++)
{
if (bf[j] == 0 && b[j] >= f[i]) // Block not allocated and big enough
{
temp = b[j] - f[i];
if (temp > highest)
{
ff[i] = j;
highest = temp;
}
}
}

if (ff[i] != -1) // Allocate the block if found


{
frag[i] = highest;
bf[ff[i]] = 1; // Mark block as allocated
}
else
{
frag[i] = -1; // Indicate no suitable block found
}
}

printf("\nFile_no:\tFile_size:\tBlock_no:\tBlock_size:\tFragment");
for (i = 0; i < nf; i++)
{
if (ff[i] != -1)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", i + 1, f[i], ff[i] + 1, b[ff[i]], frag[i]);
else
printf("\n%d\t\t%d\t\tNot Allocated", i + 1, f[i]);
}
}

OUTPUT:
Ex.NO:8(c) MEMORY ALLOCATION METHODS FOR
FIXED PARTITION

BEST FIT

AIM:
To write a C program for implementation memory allocation methods for
fixed partition using best fit.

ALGORITHM:

Step 1:Define the max as 25.


Step 2: Declare the variable frag[max],b[max],f[max],i,j,nb,nf,temp,
highest=0, bf[max],ff[max].
Step 3: Get the number of blocks,files,size of the blocks using for loop.
Step 4: In for loop check bf[j]!=1, if so temp=b[j]-f[i]
Step 5: Check lowest>temp,if so assign ff[i]=j,highest=temp
Step 6: Assign frag[i]=lowest, bf[ff[i]]=1,lowest=10000
Step 7: Repeat step 4 to step 6.
Step 8: Print file no,size,block no,size and fragment.
Step 9: Stop the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
#define MAX 25

void main() {
int blockSize[MAX], fileSize[MAX], blockAllocated[MAX] = {0}, i, j, nb, nf,
bestIdx;

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 = 0; i < nb; i++) {
printf("Block %d: ", i + 1);
scanf("%d", &blockSize[i]);
}

printf("Enter the size of the files:\n");


for (i = 0; i < nf; i++) {
printf("File %d: ", i + 1);
scanf("%d", &fileSize[i]);
}

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


bestIdx = -1;
for (j = 0; j < nb; j++) {
if (!blockAllocated[j] && blockSize[j] >= fileSize[i]) {
if (bestIdx == -1 || blockSize[j] < blockSize[bestIdx])
bestIdx = j;
}
}
if (bestIdx != -1) {
blockAllocated[bestIdx] = 1;
printf("\nFile %d allocated to Block %d", i + 1, bestIdx + 1);
} else {
printf("\nFile %d Not Allocated", i + 1);
}
}
}
OUTPUT:

RESULT:
Thus, the result for the memory allocation methods for fixed partition has been
verified and executed successfully.
Ex.NO:9(a) PAGE REPLACEMENT ALGORITHMS

FIFO

AIM:
To write a C program for implementation of FIFO page replacement algorithm.

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the necessary variables.
Step 3: Enter the number of frames.
Step 4: Enter the reference string end with zero.
Step 5: FIFO page replacement selects the page that has been in memory the
longest time and when the page must be replaced the oldest page is chosen.
Step 6: When a page is brought into memory, it is inserted at the tail of
the queue.
Step 7: Initially all the three frames are empty.
Step 8: The page fault range increases as the no of allocated frames
also increases.
Step 9: Print the total number of page faults.
Step 10: Stop the program.

PROGRAM:

#include <stdio.h>
#include <conio.h>
int main() {
int pages[100], frames[10], pageFaults = 0, capacity, numPages;
int i, j, k = 0, found;

// Input number of frames


printf("Enter the number of frames: ");
scanf("%d", &capacity);

// Input number of pages


printf("Enter the number of pages: ");
scanf("%d", &numPages);

// Input page reference string


printf("Enter the page reference string: ");
for (i = 0; i < numPages; i++) {
scanf("%d", &pages[i]);
}

// Initialize frames to -1 (indicating empty slots)


for (i = 0; i < capacity; i++) {
frames[i] = -1;
}

// FIFO Page Replacement Logic


printf("\nPage Reference\tFrames\n");
for (i = 0; i < numPages; i++) {
found = 0;

// Check if the page is already in frames


for (j = 0; j < capacity; j++) {
if (frames[j] == pages[i]) {
found = 1;
break;
}
}

// If page is not in frame, replace the oldest one (FIFO)


if (!found) {
frames[k] = pages[i]; // Replace using FIFO order
k = (k + 1) % capacity; // Circular replacement
pageFaults++;

// Display the frame status


printf("%d\t\t", pages[i]);
for (j = 0; j < capacity; j++) {
if (frames[j] != -1)
printf("%d ", frames[j]);
else
printf("- ");
}
printf("\n");
}
}
// Display total page faults
printf("\nTotal Page Faults: %d\n", pageFaults);
return 0;
}

OUTPUT:
Ex.NO:9(b) PAGE REPLACEMENT ALGORITHMS

LRU

AIM:
To write a c program to implement LRU page replacement algorithm.

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

PROGRAM:

#include <stdio.h>
#include <conio.h>
int findLRU(int time[], int n) {
int i, min = time[0], pos = 0;
for (i = 1; i < n; ++i) {
if (time[i] < min) {
min = time[i];
pos = i;
}
}
return pos;
}

int main() {
int frames[10], pages[100], time[10];
int i, j, k, pageFaults = 0, capacity, numPages, counter = 0, found, pos;
// Input number of frames
printf("Enter the number of frames: ");
scanf("%d", &capacity);

// Input number of pages


printf("Enter the number of pages: ");
scanf("%d", &numPages);

// Input page reference string


printf("Enter the page reference string: ");
for (i = 0; i < numPages; i++) {
scanf("%d", &pages[i]);
}

// Initialize frames to -1 (indicating empty slots)


for (i = 0; i < capacity; i++) {
frames[i] = -1;
}

// LRU Page Replacement Logic


printf("\nPage Reference\tFrames\n");
for (i = 0; i < numPages; i++) {
found = 0;

// Check if the page is already in frames


for (j = 0; j < capacity; j++) {
if (frames[j] == pages[i]) {
found = 1;
time[j] = counter++; // Update last used time
break;
}
}

// If page is not in frame, replace the least recently used one


if (!found) {
if (i < capacity) {
pos = i; // Directly place into an empty frame
} else {
pos = findLRU(time, capacity); // Find LRU page to replace
}
frames[pos] = pages[i];
time[pos] = counter++;
pageFaults++;

// Display the frame status


printf("%d\t\t", pages[i]);
for (k = 0; k < capacity; k++) {
if (frames[k] != -1)
printf("%d ", frames[k]);
else
printf("- ");
}
printf("\n");
}
}

// Display total page faults


printf("\nTotal Page Faults: %d\n", pageFaults);
return 0;
}

OUTPUT:
Ex.NO:9(c) PAGE REPLACEMENT ALGORITHMS

LFU

AIM:
To write C program to implement LFU page replacement algorithm.

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

PROGRAM:

#include <stdio.h>
#define MAX 100

typedef struct {
int page; // Page number
int freq; // Frequency of use
int time; // Time when the page was last used
} Frame;

// Function to find the Least Frequently Used (LFU) frame


int findLFU(Frame frames[], int capacity) {
int minFreq = frames[0].freq, minTime = frames[0].time, pos = 0;
int i; // Declare i outside the loop for compatibility
for (i = 1; i < capacity; i++) {
if (frames[i].freq < minFreq || (frames[i].freq == minFreq && frames[i].time <
minTime)) {
minFreq = frames[i].freq;
minTime = frames[i].time;
pos = i;
}
}
return pos;
}

int main() {
int numFrames, numPages, pages[MAX], pageFaults = 0, time = 0;

printf("Enter the number of frames: ");


scanf("%d", &numFrames);
if (numFrames <= 0 || numFrames > MAX) {
printf("Error: Invalid number of frames!\n");
return 1;
}

printf("Enter the number of pages: ");


scanf("%d", &numPages);
if (numPages <= 0 || numPages > MAX) {
printf("Error: Invalid number of pages!\n");
return 1;
}

printf("Enter the page reference string: ");


int i; // Declare i for the loop
for (i = 0; i < numPages; i++) {
scanf("%d", &pages[i]);
}

// Initialize memory frames


Frame frames[numFrames];
for (i = 0; i < numFrames; i++) {
frames[i].page = -1; // Empty frame
frames[i].freq = 0;
frames[i].time = 0;
}

printf("\nPage Reference\tFrames\n");
printf("----------------------------------\n");
for (i = 0; i < numPages; i++) {
int found = 0, j; // Loop variables

// Check if the page is already in frames


for (j = 0; j < numFrames; j++) {
if (frames[j].page == pages[i]) {
frames[j].freq++; // Increase frequency
frames[j].time = time++; // Update the last-used time
found = 1;
break;
}
}

// If page is not found, replace the LFU page


if (!found) {
int pos;
if (i < numFrames) {
pos = i; // If there are empty frames, use them first
} else {
pos = findLFU(frames, numFrames);
}

frames[pos].page = pages[i];
frames[pos].freq = 1;
frames[pos].time = time++;
pageFaults++;
}

// Display the frame status


printf("%d\t\t", pages[i]);
for (j = 0; j < numFrames; j++) {
if (frames[j].page != -1)
printf("%d(%d) ", frames[j].page, frames[j].freq);
else
printf("-- ");
}
printf("\n");
}
printf("\nTotal Page Faults: %d\n", pageFaults);

return 0;
}

OUTPUT:

RESULT:
Thus the result for the page replacement algorithms has been verified and
executed successfully.
Ex.NO:10 DISK SCHEDULING ALGORITHM

AIM:
To write C program to implement disk scheduling algorithm.

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

PROGRAM:

#include <stdio.h>
#include <math.h>
int size = 8;
void FCFS(int arr[],int head)
{
int seek_count = 0;
int cur_track, distance;
for(int i=0;i<size;i++)
{
cur_track = arr[i];
distance = fabs(head - cur_track);
seek_count += distance;
head = cur_track;
}
printf("Total number of seek operations:%d\n",seek_count);
printf("Seek Sequence is\n");
for (int i = 0; i < size; i++) {
printf(“%d\n”,arr[i]);
}
}
int main ()
{
int arr[8] = {176, 79, 34, 60, 92, 11, 41, 114};
int head = 50;
FCFS (arr,head);
return 0;
}
OUTPUT:

RESULT:
Thus, the result for the disk scheduling algorithm has been verified and
executed successfully.

You might also like