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

OS LAB R 23

The document is a laboratory manual for the Operating Systems Laboratory at Avanthi St. Theresa Institute of Engineering for the academic year 2025-2026. It outlines the institute's vision and mission, program outcomes, educational objectives, and specific outcomes, along with a list of experiments covering various operating system concepts and commands. The manual also includes general laboratory instructions and detailed descriptions of each experiment to be conducted by students.

Uploaded by

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

OS LAB R 23

The document is a laboratory manual for the Operating Systems Laboratory at Avanthi St. Theresa Institute of Engineering for the academic year 2025-2026. It outlines the institute's vision and mission, program outcomes, educational objectives, and specific outcomes, along with a list of experiments covering various operating system concepts and commands. The manual also includes general laboratory instructions and detailed descriptions of each experiment to be conducted by students.

Uploaded by

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

AVANTHI’SST. THERESSAINSTITUTEOF ENGG.

&
ENGG.&TECH

GARIVIDI

VizianagaramDist(AP)

Estd 2001

2025-2026

LABORATORY MANUAL

OF

Operating Systems Laboratory (R


(R-23
23 REGULATION)

Prepared by

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


LAB MANUAL CONTENT
Operating Systems Laboratory
Institute Vision & Mission, Department Vision & Mission
1. PO, PEO& PSO Statements.
2. List of Experiments
3. CO-PO Attainment
4. Experiment Code and Outputs

1. Institute Vision & Mission, Department Vision & Mission Institute Vision:
To produce Competent Engineering Graduates & Managers with a strong base of Technical &
Managerial Knowledge and the Complementary Skills needed to be Successful Professional
Engineers & Managers.
Institute Mission: To fulfill the vision by imparting Quality Technical & Management
Education to the Aspiring Students, by creating Effective Teaching/Learning Environment and
providing State – of the – Art Infrastructure and Resources.
Department Vision: To produce Industry ready Software Engineers to meet the challenges of
21st Century.
Department Mission: 
 Impart core knowledge and necessary skills in Computer Science and Engineering through
innovative teaching and learning methodology. 
 Inculcate critical thinking, ethics, lifelong learning and creativity needed for industry and
society.
Cultivate the students with all-round competencies, for career, higher education and
self- employ-ability .

2. PO, PEO& PSO Statements


PROGRAMME OUTCOMES (POs)
PO-1: Engineering knowledge - Apply the knowledge of mathematics, science, engineering
fundamentals of Computer Science& Engineering to solve complex real-life engineering problems
related to CSE.
PO-2: Problem analysis - Identify, formulate, review research literature, and analyze complex
engineering problems related to CSE and reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.

Departmentof CSE ASTC


PO-3: Design/development of solutions - Design solutions for complex engineering
problemsrelated to CSE and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, cultural, societal and environmental
considerations.
PO-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.
PO-5: Modern tool usage - Select/Create and apply appropriate techniques, resources and modern
engineering and IT tools and technologies for rapidly changing computing needs, including
prediction and modeling to complex engineering activities, with an understanding of the limitations.
PO-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 CSE professional engineering practice.
PO-7: Environment and Sustainability - Understand the impact of the CSE professional
engineering solutions in societal and environmental contexts and demonstrate the knowledge of,
and need for sustainable development.
PO-8: Ethics - Apply ethical principles and commit to professional ethics and responsibilities and
norms of the relevant engineering practices.
PO-9: Individual and team work - Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO-10: Communication - Communicate effectively on complex engineering activities with the
engineering community and with the society-at-large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, give and receive clear
instructions.
PO-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.
PO-12: Life-long learning - Recognize the need for and have the preparation and ability to engage
in independent and life-long learning in the broadcast context of technological changes.

Departmentof CSE ASTC


Program Educational Objectives (PEO’s):
PEO 1:Graduates will be prepared for analyzing, designing, developing and testing the software
solutions and products with creativity and sustainability.
PEO 2: Graduates will be skilled in the use of modern tools for critical problem solving and
analyzing industrial and societal requirements.
PEO 3:Graduates will be prepared with managerial and leadership skills for career and starting up
own firms.

Program Specific Outcomes (PSOs):


PSO 1:Develop creative solutions by adapting emerging technologies / tools for real time
applications.
PSO 2: Apply the acquired knowledge to develop software solutions and innovative mobile apps
for various automation applications.

Course Objectives:
The main objectives of the course are to
 Provide insights into system calls, file systems, semaphores,
 Develop and debug CPU Scheduling algorithms, page replacement algorithms, thread
implementation.
 Implement Banker’s Algorithms to Avoid the Dead Lock.

Course Outcomes:

After completion of the course, students will be able to


1. Trace different CPU Scheduling algorithms (L2).
2. Implement Bankers Algorithms to Avoid the Dead Lock (L3).
3. Evaluate Page replacement algorithms (L5).
4. Illustrate the file organization techniques (L4).
5. Illustrate Inter process Communication and concurrent execution of threads (L4)

Departmentof CSE ASTC


Experiments covering the Topics:
• UNIX fundamentals, commands & system calls
• CPU Scheduling algorithms, thread processing
• IPC, semaphores, monitors, deadlocks
• Page replacement algorithms, file allocation strategies
• Memory allocation strategies
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, misbehavior s 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

Departmentof CSE ASTC


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.

Departmentof CSE ASTC


INDEX

S.N EXPERIM PROGRAMMS P.g No


O ENTS
1 1 Practicing of Basic UNIX Commands.

2 2 Write programs using the following UNIX operating system calls


fork, exec, getpid, exit, wait, close, stat, opendir and readdir

3 3 Simulate UNIX commands like cp, ls, grep, etc.,

4 4 Simulate the following CPU scheduling algorithms


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

5 5 Control the number of ports opened by the operating system with


a) Semaphore b) Monitors.

6 6 Write a program to illustrate concurrent execution of threads using


pthreads library

7 7 Write a program to solve producer-consumer problem using


Semaphores.
8 8 Implement the following memory allocation methods for fixed
partition
a) First fit b) Worst fit c) Best fit
9 9 Simulate the following page replacement algorithms
a) FIFO b) LRU c) LFU

10 10 Simulate Paging Technique of memory management.

11 11 Implement Bankers Algorithm for Dead Lock avoidance and


prevention
12 12 Simulate the following file allocation strategies
a) Sequential b) Indexed c) Linked

Departmentof CSE ASTC


Avanthi ST.theresa engineering college
Department: COMPUTER SCIENCE & ENGINEERING (CSE)
Course Outcome Attainment - Internal Assessments
Name of the faculty : SIRELA MEENA Academic Year: 2018-2019

Branch & Section: COMPUTER SCIENCE Exam:


& ENGINEERING
Course: Operating Systems Laboratory Semester: II-II SEM

Course Outcomes Attainment


Level
Ensure the development of applied skills in operating systems related areas. 3
Able to write software routines modules or implementing various concepts 3
of operating
system
Understand process life cycle and able to tell process status. 3
Understand the concepts of process scheduling, synchronization and its 3
Implementation.
Determine the prevention, avoidance, detection, recovery mechanism of 3
deadlock.
Average Attainment 3
Overall Course Attainment 3

Departmentof CSE ASTC


Experiment-1
AIM: Practicing of Basic UNIX Commands.

cd Command :
cd command is used to change the directory.
cd linux-command
This command will take you to the sub-directory(linux -command) from its parent
directory.
Ex:
cd ..
This will change to the parent-directory from the current working directory/sub-
directory.
cd ~
This command will move to the user's home directory which is "/home/username".

cat Command

The cat command is a multi-purpose utility in the Linux system. It can be used to create a file,
display content of the file, copy the content of one file to another file, and more.
Syntax:
1. cat [OPTION]... [FILE]..
To create a file, execute it as follows:
1. cat ><file name>
2. // Enter file content
Press "CTRL+ D" keys to save the file. To display the content of the file, execute
it as follows:
1. cat <file name>
Output:
rm command:

rm linux command is used to remove/delete the file from the directory.


To Remove / Delete a file: Here rm command will remove/delete the file
file1.txt.rm file1.txt
To delete a directory tree:
rm -ir tmp
This rm command recursively removes the contents of all sub-directories of the
tmp directory, prompting you regarding the removal of each file, and then
removes the tmp directory itself.
To remove more files at once: rm command removes file1.txt and file2.txt files at
the same time.rm file1.txt file2.txt
cp command:
cp command copy files from one location to another. If the destination is an
existing file, then the file is overwritten; if the destination is an existing directory,
the file is copied into the directory (the directory is not overwritten).
Copy two files: cp file1.txt file2.txt
The above cp command copies the content of file1.txt to file2.txt

ls command:
ls command liststhe files and directories under current working directory. Display root
directory contents: ls / Lists the contents of root directory.
Display hidden files and directories: ls -a lists all entries including hidden files and directories.
Display inode information: ls –I
Output:
mkdir command: Use this command to create one or more new directories.
Include one or more instances of the “<DIRECTORY” variable (separating each
with a white space), and set each to the complete path to the new directory to be
created.
mkdir OPTION <DIRECTORY>

rmdir Command
The rmdir command is used to delete a directory.
Syntax:
1. rmdir <directory name>

mv command:
The mv command is used to move a file or a directory form one location to
another location.
Syntax:
1. mv <file name><directory path>
Output:

ps Command:

ps command is used to report the process status. ps is the short name for Process
Status.
$ ps # show process info
$ ps -f # : Displays full information about currently running processes.
man Command
The "man" is a short term for manual page. In unix like operating systems such
as linux, man is an interface to view the system's reference manual.
A user can request to display a man page by simply typing man followed by a
space and then argument. Here its argument can be a command, utility or
function.
A manual page associated with each of these arguments is displayed
Syntax of man:
man [option(s)] keyword(s)
But generally [option(s)] are not used. Only keyword is written as an argument.
For example,
1. man ls
This command will display all the information about 'ls' command as shown in the
Picture.

who
The who command gives the information about the users logged on to the system.
Syntax:
1. who

pwd Command
The pwd command is used to display the location of the current working directory.
Syntax:
1. pwd

Output:
touch – Create an empty file or update the timestamp of an existing file:
touch file_name
find – Find files by name in the current directory:
find . -name "filename"
grep – Search text within files
Search for a specific word inside a file:grep "word" file_name
Search for a word in all files in the current directory: grep -r "word" .

chmod – Change file permissions


Change permissions of a file (e.g., make it executable):chmod +x file_name
top – Display system information
Show the system’s resource usage, including CPU and memory:top

ps –Display current running processes: ps


kill – Kill a process by its PID (Process ID):kill process_id
history: Show a list of previously used commands :history
clear – Clear the terminal screen: clear
more command
The more command is quite similar to the cat command, as it is used to display the file
content in the same way that the cat command does. The only difference between both
commands is that, in case of larger files, the more command displays screen-ful output at a
time.
In more command, the following keys are used to scroll the page:
ENTER key: To scroll down page by line.
Spacebar: To move to the next page.
B-key: To move to the previous page.
/key: To search the string.
Syntax:
1. more<filename>
Output:
date Command
The date command is used to display date, time, time-zone, and more.
Syntax:
1. Date
Output:

cal Command
The cal command is used to display the current month's calendar with the
current date highlighted.
Syntax:
1. cal<

Output:

time Command:
The time command is used to display the time to execute a command.
Syntax:
1. time
Output:
echo
The echo command in Linux is a built built-in
in command that allows users to display lines of text or
strings that are passed as arguments. It is commonly used in shell scripts and batch files to
output status text to the screen or a file.
Syntax of `echo` command
mmand in Linux
echo [option] [string]
Here,
[options] = The various options available for modifying the behavior of the `echo` command
[string] = It is the string that we want to display.

Echo Command Options


The echo command has several arguments. The fo
following
llowing table presents commonly
used echo command options.

Option Description

-n Displays the output while omitting the newline after it.

-E The default option. Disables the interpretation of escape characters.

-e Enables the interpretation of escape characters.

Displays a help message with information about the echo command and its
--help
options.

--version Prints the echo command version information.

finger
The ‘finger’ command is a powerful utility in Linux used to display information about users
logged into the system. This command is commonly used by system administrators to retrieve
detailed user information, including login name, full name, idle time, login time, and sometimes
the user’s email address. The ‘finger’
finger’ command offers more comprehensive details compared to
the ‘pinky’ command, which is a lighter version with limited output.
Syntax: $sudo apt-get install finger

Logout
Logout command allows you to programmatically logout from your session. causes the
session manager to take the requested action immediately.
Syntax:$logout

Example:

Shutdown
The `shutdown` operation in Linux is a crucial command for managing system power states,
allowing administrators to halt safely, power off, or reboot the system. This command provides
flexibility in scheduling downtimes, ensuring minimal disruption to users and processes. In this
article, we will explore the `shutdown` command with practical examples, illustrating how to use
its various options to control system behavior effectively.
Syntax:
shutdown [OPTIONS] [TIME] [MESSAGE]
 OPTIONS:: Various options to control the shutdown process, such as halting, powering
off, or rebooting the system.
 TIME: Specifies
ies when to perform the shutdown, either immediately, after a specified
delay, or at a specific time.
 MESSAGE:: An optional message that is broadcasted to all logged
logged-in
in users, informing
them of the scheduled shutdown.
Key Options of the Shutdown Command
The following are the options of shutdown command in Linux:
‘-r’: Requests that the system be rebooted after it has been brought down.
‘-h’: Requests that the system be either halted or powered off after it has been brought down,
with the choice as to which left up to the system.
‘-H’: Requests that the system be halted after it has been brought down.
‘-P’: Requests that the system be powered off after it has been brought down.
‘-c’: Cancels a running shutdown. TIME is not specified with this option, the first argument is
MESSAGE.
‘-k’: Only send out the warning messages and disable logins, do not actually bring the system
down.
EXPERIMENT 2
Aim: Write programs using the following UNIX operating system calls fork, exec, getpid, exit,
wait, close, stat, opendir and readdir.
1. fork() - Create a child process
Source Code:
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
// Error
perror("fork failed");
return 1;
}
if (pid == 0) {
// Child process
printf("This is the child process with PID: %d\n", getpid());
} else {
// Parent process
printf("This is the parent process with PID: %d\n", getpid());
}
return 0;
}

Expected Output:

This is the parent process with PID: 12345


This is the child process with PID: 12346

2. exec() - Replace current process with another

Source Code:

#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// Child process
printf("Child process before exec\n");
execlp("/bin/ls", "ls", "-l", NULL);
// This line won't be executed if exec() is successful
perror("exec failed");
} else if (pid > 0) {
// Parent process

Departmentof CSE ASTC


wait(NULL); // Wait for the child to finish
printf("Parent process\n");
} else {
perror("fork failed");
}
return 0;
}

Expected Output:

Child process before exec


<list of files in the current directory>
Parent process

3. getpid() - Get the process ID

Source Code:

#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = getpid();
printf("The process ID is: %d\n", pid);
return 0;
}

Expected Output:

The process ID is: 12345

4. exit() - Exit the program

Source Code:

#include <stdio.h>
#include <stdlib.h>
int main() {
printf("This is the main process.\n");
exit(0); // Exit with a status code of 0
printf("This line won't be printed.\n");
}

Expected Output:

This is the main process.

5. wait() - Wait for child process

Departmentof CSE ASTC


Source Code:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// Child process
printf("Child process is running.\n");
sleep(2); // Simulate some work
printf("Child process finished.\n");
return 0;
} else if (pid > 0) {
// Parent process
printf("Parent process waiting for child to finish.\n");
wait(NULL); // Wait for child process to terminate
printf("Parent process finished.\n");
} else {
perror("fork failed");
}
return 0;
}

Expected Output:

Parent process waiting for child to finish.


Child process is running.
Child process finished.
Parent process finished.

6. close() - Close a file descriptor

Source Code:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("test.txt", O_CREAT | O_WRONLY, 0666);
if (fd == -1) {
perror("Error opening file");
return 1;
}
write(fd, "Hello, World!\n", 14);
close(fd); // Close the file descriptor
printf("File closed successfully.\n");

Departmentof CSE ASTC


return 0;
}
Expected Output:

File closed successfully.

7. stat() - Get file status information

Source Code:

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
struct stat fileStat;
if (stat("test.txt", &fileStat) == -1) {
perror("Error getting file status");
return 1;
}
printf("File size: %ld bytes\n", fileStat.st_size);
printf("Last modified: %ld\n", fileStat.st_mtime);
return 0;
}

Expected Output:

File size: 14 bytes


Last modified: 1613583458

8. opendir() and readdir() - Read a directory's contents

Source Code:

#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
if (dir == NULL) {
perror("Error opening directory");
return 1;
}
printf("Listing files in the current directory:\n");
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;

Departmentof CSE ASTC


}

Expected Output:

sql
Copy
Listing files in the current directory:
.
..
test.txt
program.c

Departmentof CSE ASTC


EXPERIMENT -3
Aim: Simulate UNIX commands like cp, Is, grep, etc..
1. Simulating ls Command
The ls command lists files and directories in the current directory. Here's how to simulate it
in C:

Source Code:
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir = opendir(".");
struct dirent *entry;
if (dir == NULL) {
perror("Error opening directory");
return 1;
}
printf("Files and directories in the current directory:\n");
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
return 0;
}

Expected Output:

Files and directories in the current directory:


.
..
file1.txt
file2.txt
folder1
program.c

2. Simulating “cp” Command


The cp command copies files from one location to another. Here’s how to simulate it in C:
Source Code:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
void copy_file(const char *source, const char *destination) {
int src_fd = open(source, O_RDONLY);
if (src_fd == -1) {
perror("Error opening source file");
return;

Departmentof CSE ASTC


}
int dest_fd = open(destination, O_CREAT | O_WRONLY, 0666);
if (dest_fd == -1) {
perror("Error opening destination file");
close(src_fd);
return;
}
char buffer[1024];
ssize_t bytes_read, bytes_written;
while ((bytes_read = read(src_fd, buffer, sizeof(buffer))) > 0) {
bytes_written = write(dest_fd, buffer, bytes_read);
if (bytes_written == -1) {
perror("Error writing to destination file");
break;
}
}
close(src_fd);
close(dest_fd);
printf("File copied successfully.\n");
}
int main() {
const char *source = "file1.txt";
const char *destination = "file1_copy.txt";
copy_file(source, destination);
return 0;
}

Expected Output:

File copied successfully.

3. Simulating “grep” Command


The grep command searches for a pattern in a file. Here's how to simulate it in C:

Source Code:

#include <stdio.h>
#include <string.h>
void grep_pattern(const char *filename, const char *pattern) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return;
}
char line[1024];
int line_number = 1;
while (fgets(line, sizeof(line), file)) {
if (strstr(line, pattern)) {

Departmentof CSE ASTC


printf("Line %d: %s", line_number, line);
}
line_number++;
}
fclose(file);
}
int main() {
const char *filename = "file1.txt";
const char *pattern = "hello"; // Replace with the pattern you want to search
grep_pattern(filename, pattern);
return 0;
}

Expected Output:
(if "hello" is in the file)

Line 2: hello world


Line 4: hello again

4. Simulating “cat” Command


The cat command displays the contents of a file. Here's how to simulate it in C:

Source Code:

#include <stdio.h>
void cat_file(const char *filename) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
perror("Error opening file");
return;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
}
int main() {
const char *filename = "file1.txt";
cat_file(filename);
return 0;
}

Expected Output:
(assuming file1.txt contains some text):
This is the content of file1.txt.
It has multiple lines.

Departmentof CSE ASTC


5. Simulating “rm” Command
The rm command removes a file. Here’s how to simulate it in C:

Source Code:

#include <stdio.h>
#include <stdlib.h>
void remove_file(const char *filename) {
if (remove(filename) == 0) {
printf("File '%s' deleted successfully.\n", filename);
} else {
perror("Error deleting file");
}
}
int main() {
const char *filename = "file1.txt";
remove_file(filename);
return 0;
}

Expected Output:

File 'file1.txt' deleted successfully.


If the file doesn't exist, it will print an error message.

6. Simulating “mkdir” Command


The mkdir command creates a directory. Here's how to simulate it in C:

Source Code:

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
void create_directory(const char *dir_name) {
if (mkdir(dir_name, 0777) == 0) {
printf("Directory '%s' created successfully.\n", dir_name);
} else {
perror("Error creating directory");
}
}
int main() {
const char *dir_name = "new_folder";
create_directory(dir_name);
return 0;
}

Departmentof CSE ASTC


Expected Output:
Directory 'new_folder' created successfully.
If the directory already exists, it will print an error message.

7. Simulating “pwd” Command


The pwd command prints the current working directory. Here's how to simulate it in C:

Source Code:

#include <stdio.h>
#include <unistd.h>
int main() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
printf("Current working directory: %s\n", cwd);
} else {
perror("Error getting current directory");
}
return 0;
}
Expected Output:
Current working directory: /home/user/Documents

Departmentof CSE ASTC


Experiment-4

Simulate the following CPU scheduling algorithms

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


Aim: Write a c program to simulate the CPU scheduling algorithm to FCFS :
FCFS CPU SCHEDULING ALGORITHM
For FCFS scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times.
The scheduling is performed on the basis of arrival time of the processes irrespective of their other
parameters. Each process will be executed according to its arrival time. Calculate the waiting time and
turnaround time of each of the processes accordingly.
Source Code:
#include<stdio.h>
#include<conio.h>
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++)
{
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],

Departmentof CSE ASTC


tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
getch();
}

INPUT
Enterthe number of processes -- 3
Enter Burst Time for Process 0 -- 24
Enter Burst Time for Process 1 -- 3
Enter Burst Time for Process 2 -- 3

OUTPUT

PROCESS BURST TIME WAITING TIME TURN AROUND TIME


P0 24 0 24
P1 3 24 27
P2 3 27 30

Average Waiting Time-- 17.000000


Average Turnaround Time -- 27.000000

Departmentof CSE ASTC


AIM: Write a c program to simulate the CPU scheduling algorithm to SJF:

SJF CPU SCHEDULING ALGORITHM :

For SJF scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times.
Arrange all the jobs in order with respect to their burst times. There may be two jobs in queue with the
same execution time, and then FCFS approach is to be performed. Each process will be executed
according to the length of its burst time. Then calculate the waiting time and turnaround time of each
of the processes accordingly.

Source Code:

#include<stdio.h>
#include<conio.h>
main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
clrscr();
printf("\n Enter 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;
}
np=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];

Departmentof CSE ASTC


tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \t BURST 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", p[i], bt[i], wt[i], tat[i]);printf("\nAverage Waiting Time
-- %f", wtavg/n);
printf("\n Average Turnaround Time -- %f", tatavg /n);
getch();
}

INPUT
Enter the number of processes -- 4
Enter Burst Time for Process 0 -- 6
Enter Burst Time for Process 1 -- 8
Enter Burst Time for Process 2 -- 7
Enter Burst Time for Process 3 -- 3

OUTPUT:

PROCESS BURST TIME WAITING TIME URNAROUND TIME


P3 3 0 3
P0 6 3 9
P2 7 9 16
P1 8 16 24

Average Waiting Time -- 7.000000


Average Turnaround Time -- 13.000000

Departmentof CSE ASTC


AIM: Write a c program to simulate the CPU scheduling algorithm to PRIORITY:

PRIORITY CPU SCHEDULING ALGORITHM

For priority scheduling algorithm, read the number of processes/jobs in the system, their CPU burst
times, and the priorities. Arrange all the jobs in order with respect to their priorities. There may be two
jobs in queue with the same priority, and then FCFS approach is to be performed. Each process will be
executed according to its priority. Calculate the waiting time and turnaround time of each of the
processes accordingly.

Source Code:

#include<stdio.h>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];
}
printf("\n PROCESS \t\t PRIORITY \t BURST TIME \t WAITING TIME \t TURNAROUND
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("\n Average Waiting Time is --- %f",wtavg/n);

Departmentof CSE ASTC


printf(" \n Average Turnaround Time is --- %f",tatavg/n);getch();
}

INPUT
Enter the number of processes --5
Enter the Burst Time &Priority of Process 0 --- 10
Enter the Burst Time & Priority of Process 1 --- 1
Enter the Burst Time & Priority of Process 2 --- 2
Enter the Burst Time & Priority of Process 3 --- 1
Enter the Burst Time & Priority of Process 4 --- 5

OUTPUT
PROCESS PRIORITY BURST TIME WAITING TIME TURNAROUND TIME
1 1 1 0 1
4 2 5 1 6
0 3 10 6 16
2 4 2 16 18
3 5 1 18 19
Average Waiting Time is --- 8.200000
Average Turnaround Time is --- 12.000000

Departmentof CSE ASTC


AIM: Write a c program to simulate the CPU scheduling algorithm to ROUND ROBIN:

ROUND ROBIN CPU SCHEDULING ALGORITHM


For round robin scheduling algorithm, read the number of processes/jobs in the system, their
CPU burst times, and the size of the time slice. Time slices are assigned to each process in
equal portions and in circular order, handling all processes execution. This allows every
process to get an equal chance. Calculate the waiting time and turnaround time of each of
the processes accordingly.

Source Code:

#include<stdio.h>
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("\n Enter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\n Enter 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];
}

Departmentof CSE ASTC


printf("\n The Average Turnaround time is -- %f",att /n);
printf("\n The Average Waiting time is -- %f ",awt /n);
printf("\n\t PROCESS \t BURST TIME \t WAITING TIME \t TURNAROUND 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();
}

INPUT

Enter the no of processes – 3


Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 -- 3
Enter the size of time slice – 3
PROCESS BURST TIME AITING TIME TURNAROUND TIME
1 24 6 30
2 3 4 7
3 3 7 10

OUTPUT

The Average Turnaround time is – 15.666667


The Average Waiting time is -- 5.66666

Departmentof CSE ASTC


EXPERIMENT-5
Control the number of ports opened by the operating system with
a) Semaphore b)Monitors

Aim: Write a c program the number of ports opened by the operating system with
Semaphore
Semaphore: A synchronization primitive that is used to control access to a shared
resource by multiple processes in a concurrent system. It is typically used to restrict
the number of processes that can access a resource concurrently. In this case, we can
use a semaphore to limit the number of open ports.
Source Code:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define MAX_PORTS 3 // Maximum number of open ports
sem_t port_semaphore; // Semaphore to control the number of open ports
void* open_port(void* arg) {
int process_id = *((int*)arg);
printf("Process %d trying to open a port...\n", process_id); // Wait for a free port
sem_wait(&port_semaphore);
printf("Process %d opened a port.\n", process_id);
sleep(2); // Simulating port usage for 2 seconds // Release the port
printf("Process %d closed the port.\n", process_id);
sem_post(&port_semaphore);
return NULL;
}
int main() {
pthread_t processes[5];
int process_ids[5] = {1, 2, 3, 4, 5};
// Initialize semaphore with MAX_PORTS available
sem_init(&port_semaphore, 0, MAX_PORTS); //Create 5 processes to simulate port opening
for (int i = 0; i < 5; i++) {
pthread_create(&processes[i], NULL, open_port, &process_ids[i]);
}
// Wait for all threads to finish
for (int i = 0; i < 5; i++) {
pthread_join(processes[i], NULL);
}

Departmentof CSE ASTC


// Destroy the semaphore
sem_destroy(&port_semaphore);
return 0;
}

Expected Output:
Process 1 trying to open a port...
Process 1 opened a port.
Process 2 trying to open a port...
Process 2 opened a port.
Process 3 trying to open a port...
Process 3 opened a port.
Process 4 trying to open a port...
Process 4 is waiting for a free port.
Process 5 trying to open a port...
Process 5 is waiting for a free port.
Process 1 closed the port.
Process 4 opened a port.
Process 2 closed the port.
Process 5 opened a port.
Process 3 closed the port.
Process 4 closed the port.
Process 5 closed the port.

Departmentof CSE ASTC


Aim: Write a c program the number of ports opened by the operating system with
Monitors.

Monitors: A synchronization construct that allows safe access to shared resources


through a lock mechanism. A monitor ensures that only one thread can execute the
critical section of code at any point in time. Monitors are typically associated with
condition variables, which are used to block or signal processes.
Monitors are a higher-level synchronization construct. In C, we can simulate
monitors using mutexes and condition variables. We’ll create a monitor to control
the number of open ports, and processes will wait for a port to be available if there
are no free ports.
Source Code:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define MAX_PORTS 3 // Maximum number of open ports
pthread_mutex_t port_mutex = PTHREAD_MUTEX_INITIALIZER;// Mutex to ensure mutual exclusion
pthread_cond_t port_cond = PTHREAD_COND_INITIALIZER;// Condition variable to signal when a port is
available

int available_ports = MAX_PORTS; // Number of available ports


void* open_port(void* arg) {
int process_id = *((int*)arg);
pthread_mutex_lock(&port_mutex); // Enter critical section
while (available_ports == 0) {
printf("Process %d is waiting for a free port...\n", process_id);
pthread_cond_wait(&port_cond, &port_mutex); // Wait until a port is released
}
// Open the port available_ports--;
printf("Process %d opened a port.Available ports: %d\n", process_id, available_ports);

Departmentof CSE ASTC


pthread_mutex_unlock(&port_mutex); // Exit critical section
sleep(2); // Simulating port usage for 2 seconds
// Close the port
pthread_mutex_lock(&port_mutex); // Re-enter critical section
available_ports++;
printf("Process %d closed the port. Available ports: %d\n", process_id, available_ports);
pthread_cond_signal(&port_cond); // Signal other waiting processes that a port is available
pthread_mutex_unlock(&port_mutex); // Exit critical section
return NULL;
}
int main() {
pthread_t processes[5];
int process_ids[5] = {1, 2, 3, 4, 5}; // Create 5 processes to simulate port
opening
for (int i = 0; i < 5; i++) {
pthread_create(&processes[i], NULL, open_port, &process_ids[i]);
}
// Wait for all threads to finish
for (int i = 0; i < 5; i++) {
pthread_join(processes[i], NULL);
}
// Destroy the mutex and condition variable
pthread_mutex_destroy(&port_mutex);
pthread_cond_destroy(&port_cond);
return 0;
}

Departmentof CSE ASTC


Explanation:
We use a mutex (port_mutex) to ensure that only one process can access the critical
section at a time.
The condition variable (port_cond) allows processes to wait when there are no
available ports and be notified when a port becomes available.
The processes enter the critical section, check if a port is available, and if not, they
wait for the condition variable to be signaled.
After finishing the task, the process releases the port and signals other waiting
processes.
Expected Output:
Process 1 opened a port. Available ports: 2
Process 2 opened a port. Available ports: 1
Process 3 opened a port. Available ports: 0
Process 4 is waiting for a free port…
Process 5 is waiting for a free port…
Process 1 closed the port. Available ports: 1
Process 4 opened a port. Available ports: 0
Process 2 closed the port. Available ports: 1
Process 5 opened a port. Available ports: 0
Process 3 closed the port. Available ports: 1
Process 4 closed the port. Available ports: 2
Process 5 closed the port. Available ports: 3

Departmentof CSE ASTC


EXPERIMENT-6
Aim:
Write a program to illustrate concurrent execution of threads using pthreads library.
Program to Illustrate Concurrent Execution of Threads:

Source Code:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void* print_thread_info(void* arg) {
// Get the thread ID using pthread_self()
pthread_t thread_id = pthread_self();
// Print the thread ID
printf("Thread ID: %lu is executing\n", (unsigned long)thread_id);
// Simulate some work being done by sleeping for 2 seconds
sleep(2);
printf("Thread ID: %lu has finished execution\n", (unsigned long)thread_id);
return NULL;
}
int main() {
pthread_t threads[5]; // Array to hold thread identifiers
// Create 5 threads
for (int i = 0; i < 5; i++) {
if (pthread_create(&threads[i], NULL, print_thread_info, NULL) != 0) {
perror("Thread creation failed");
return 1;
}
}
// Wait for all threads to finish
for (int i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
printf("All threads have finished execution\n");
return 0;
}

Departmentof CSE ASTC


Explanation of the Program:
pthread_create: This function is used to create new threads. It takes the thread identifier,
attributes (which are set to NULL here), the function to execute (print_thread_info), and the
argument for the function (NULL in this case).
pthread_self: This function retrieves the ID of the current thread.
sleep: This function is used to simulate work in the thread (to allow the concurrent nature of
the execution to be visible).
pthread_join: This function waits for each thread to finish its execution before continuing in
the main thread. It ensures that the program doesn't terminate before the threads finish.

Expected Output:
Thread ID: 140438428383744 is executing
Thread ID: 140438419991040 is executing
Thread ID: 140438411598336 is executing
Thread ID: 140438403205632 is executing
Thread ID: 140438394812928 is executing
Thread ID: 140438428383744 has finished execution
Thread ID: 140438419991040 has finished execution
Thread ID: 140438411598336 has finished execution
Thread ID: 140438403205632 has finished execution
Thread ID: 140438394812928 has finished execution
All threads have finished execution

Departmentof CSE ASTC


EXPERIMENT-7
Aim: Write a program to solve producer-consumer problem using Semaphores

DESCRIPTION :
Producer-consumer problem, is a common paradigm for cooperating processes. A producer
process produces information 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. A producer can produce one item while the consumer is
consuming another item. 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(“\n Buffer is Full”);
else
{
printf(“\nEnter the value: “);
scanf(“%d”, &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
Break;
case 2: if(in == out)
printf(“\n Buffer is Empty”);
else
{
consume = buffer[out];
printf(“\n The consumed value is %d”, consume);out = (out+1)%bufsize;
}
Break;
}

Departmentof CSE ASTC


}}

OUTPUT

1. Produce 2. Consume 3. Exit Enter your choice: 2


Buffer is Empty
1. Produce 2. Consume 3. Exit Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit Enter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. Exit Enter your choice: 3

OUTPUT
2. Produce 2. Consume 3. Exit Enter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. Exit Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit Enter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. Exit Enter your choice: 3

Departmentof CSE ASTC


EXPERIMENT: 8
Aim: Implement the following memory allocation methods for fixed partition
a) First fit b) Worst fit c) Best fit

The Memory Allocation Problem is a common problem in operating systems where we need
to assign memory blocks to processes. The three common techniques for fixed partition
memory allocation are:
1. First Fit
2. Worst Fit
3. Best Fit
First Fit: Allocates the first available memory block that is large enough to hold the process.
Worst Fit: Allocates the largest available memory block that is large enough to hold the
process.
Best Fit: Allocates the smallest available memory block that is large enough to hold the
process, leaving the smallest leftover fragment.
Source Code:
#include <stdio.h>
#define MEMORY_BLOCKS 10 // Number of memory blocks
#define PROCESSES 5 // Number of processes
// Function to implement First Fit memory allocation
void first_fit(int memory[], int block_size[], int processes[], int process_size[]) {
printf("\n First Fit Memory Allocation:\n");
for (int i = 0; i < PROCESSES; i++) {
int allocated = 0;
for (int j = 0; j < MEMORY_BLOCKS; j++) {
if (memory[j] == 0 && block_size[j] >= process_size[i]) {
// Allocate memory
memory[j] = process_size[i];
printf("Process %d of size %d allocated to block %d of size %d\n", i + 1,
process_size[i], j + 1, block_size[j]);
allocated = 1;
break;
}
}
if (!allocated) {
printf("Process %d of size %d could not be allocated\n", i + 1, process_size[i]);
}
}
}
// Function to implement Worst Fit memory allocation
void worst_fit(int memory[], int block_size[], int processes[], int process_size[]) {
printf("\n Worst Fit Memory Allocation:\n");

Departmentof CSE ASTC


for (int i = 0; i < PROCESSES; i++) {
int max_size = -1;
int block_index = -1;
for (int j = 0; j < MEMORY_BLOCKS; j++) {
if (memory[j] == 0 && block_size[j] >= process_size[i]) {
int remaining_space = block_size[j] - process_size[i];
if (remaining_space > max_size) {
max_size = remaining_space;
block_index = j;
}
}
}
if (block_index != -1) {
memory[block_index] = process_size[i];
printf("Process %d of size %d allocated to block %d of size %d\n", i + 1,
process_size[i], block_index + 1, block_size[block_index]);
} else {
printf("Process %d of size %d could not be allocated\n", i + 1, process_size[i]);
}
}
}
// Function to implement Best Fit memory allocation
void best_fit(int memory[], int block_size[], int processes[], int process_size[]) {
printf("\n Best Fit Memory Allocation:\n");
for (int i = 0; i < PROCESSES; i++) {
int min_size = 10000; // A large number to track minimum leftover space
int block_index = -1;
for (int j = 0; j < MEMORY_BLOCKS; j++) {
if (memory[j] == 0 && block_size[j] >= process_size[i]) {
int remaining_space = block_size[j] - process_size[i];
if (remaining_space < min_size) {
min_size = remaining_space;
block_index = j;
}
}
}
if (block_index != -1) {
memory[block_index] = process_size[i];
printf("Process %d of size %d allocated to block %d of size %d\n", i + 1,
process_size[i], block_index + 1, block_size[block_index]);
} else {
printf("Process %d of size %d could not be allocated\n", i + 1, process_size[i]);
}
}
}
int main() {
// Initialize memory blocks and their sizes
int memory[MEMORY_BLOCKS] = {0}; // All memory blocks are initially empty

Departmentof CSE ASTC


int block_size[MEMORY_BLOCKS] = {100, 500, 200, 300, 600, 400, 700, 800, 150, 250};
// Sizes of memory blocks

// Initialize process sizes


int process_size[PROCESSES] = {212, 417, 112, 426, 300};

// First fit allocation


first_fit(memory, block_size, NULL, process_size);

// Reset memory for the next allocation


for (int i = 0; i < MEMORY_BLOCKS; i++) memory[i] = 0;

// Worst fit allocation


worst_fit(memory, block_size, NULL, process_size);

// Reset memory for the next allocation


for (int i = 0; i < MEMORY_BLOCKS; i++) memory[i] = 0;

// Best fit allocation


best_fit(memory, block_size, NULL, process_size);

return 0;
}

Explanation:

First Fit Allocation:

The function first_fit checks each memory block in the order they appear. The first block that
is large enough to fit the process is allocated.

Worst Fit Allocation:

The function worst_fit looks for the largest block that is large enough to accommodate the
process. If multiple blocks are available, it chooses the one with the largest remaining space
after allocation.

Best Fit Allocation:

The function best_fit looks for the smallest block that can still accommodate the process. It
aims to minimize wasted space by selecting the block with the smallest leftover space after
allocation.

Memory Initialization:

The array memory keeps track of the allocated memory. Initially, all entries are set to 0,
indicating that the blocks are unallocated.
The block_size array represents the sizes of the memory blocks available.

Departmentof CSE ASTC


Process Sizes:

The process_size array contains the sizes of the processes that need to be allocated to the
memory blocks.

Function Calls:

The main function calls each of the three allocation methods: first_fit, worst_fit, and best_fit,
with appropriate resetting of the memory between calls to simulate independent allocation
methods.

Expected Output:

First Fit Memory Allocation:


Process 1 of size 212 allocated to block 1 of size 100
Process 2 of size 417 allocated to block 2 of size 500
Process 3 of size 112 allocated to block 3 of size 200
Process 4 of size 426 allocated to block 5 of size 600
Process 5 of size 300 allocated to block 6 of size 400

Worst Fit Memory Allocation:


Process 1 of size 212 allocated to block 9 of size 250
Process 2 of size 417 allocated to block 5 of size 600
Process 3 of size 112 allocated to block 3 of size 200
Process 4 of size 426 allocated to block 7 of size 700
Process 5 of size 300 allocated to block 8 of size 800

Best Fit Memory Allocation:


Process 1 of size 212 allocated to block 1 of size 100
Process 2 of size 417 allocated to block 5 of size 600
Process 3 of size 112 allocated to block 3 of size 200
Process 4 of size 426 allocated to block 6 of size 400
Process 5 of size 300 allocated to block 8 of size 250

Departmentof CSE ASTC


EXPERIMENT : 9
AIM: Simulate the following page replacement algorithms a) FIFO b) LRU
c) LFU

DESCRIPTION
Page replacement is basic to demand paging. It completes the separation between logical
memory and physical memory. With this mechanism, an enormous virtual memory can be
provided for programmers on a smaller physical memory. There are many different page-
replacement algorithms.
Every operating system probably has its own replacement scheme. A FIFO replacement
algorithm associates with each page the time when that page was brought into memory. When
a page must be replaced, the oldest page is chosen. If the recent past is used as an
approximation of the near future, then the page that has not been used for the longest period of
time can be replaced. This approach is the Least Recently Used (LRU) algorithm. LRU
replacement associates with each page the time of that page's last use. When a page must be
replaced, LRU chooses the page that has not been used for the longest period of time. Least
frequently used (LFU) page-replacement algorithm requires that the page with the smallest
count be replaced. The reason for this selection is that an actively used page should have a
large reference count.

a) FIFO PAGEREPLACEMENT ALGORITHM

Source Code:

#include<stdio.h>
#include<conio.h>main()
{
int i, j, k, f, pf=0, count=0, rs[25], m[10], n;
clrscr();
printf("\n Enter the length of reference string -- ");
scanf("%d",&n);
printf("\n Enter the reference string -- ");
for(i=0;i<n;i++)
scanf("%d",&rs[i]);
printf("\n Enter no. of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
m[i]=-1;
printf("\n The Page Replacement Process is -- \n");
for(i=0;i<n;i++)
{
for(k=0;k<f;k++)
{
}
if(k==f)
{

Departmentof CSE ASTC


}
if(m[k]==rs[i])
break;
m[count++]=rs[i];
pf++;
for(j=0;j<f;j++)
printf("\t%d",m[j]);
if(k==f)
printf("\tPF No. %d",pf);
printf("\n");
if(count==f)
count=0;
}
printf("\n The number of Page Faults using FIFO are %d",pf);
getch();
}

INPUT:
Enter the length of reference string – 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter no. of frames -- 3

OUTPUT

The Page Replacement Process is –


-1 -1 PF No. 1
0 -1 PF No. 2
0 1 PF No. 3
0 1 PF No. 4
0 1
3 1 PF No. 5
3 0 PF No. 6
3 0 PF No. 7
2 0 PF No. 8
2 3 PF No. 9
2 3 PF No. 10
2 3
2 3
1 3 PF No. 11
1 2 PF No. 12
1 2
1 2
1 2 PF No. 13
0 2 PF No. 14
0 1 PF No. 15
The number of Page Faults using FIFO are 15

Departmentof CSE ASTC


b) LRU PAGE REPLACEMENT ALGORITHM

Source Code:

#include<stdio.h>
int main()
{
int m, n, position, k, l;
int a = 0, b = 0, page_fault = 0;
int total_frames = 3;
int frames[total_frames];
int temp[total_frames];
int pages[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3, 6, 1, 2, 4, 3};
int total_pages = sizeof(pages)/sizeof(pages[0]);
for(m = 0; m < total_frames; m++){
frames[m] = -1;
}
for(n = 0; n < total_pages; n++)
{
printf("%d: ", pages[n]);
a = 0, b = 0;
for(m = 0; m < total_frames; m++)
{
if(frames[m] == pages[n])
{
a = 1;
b = 1;
break;
}
}
if(a == 0)
{
for(m = 0; m < total_frames; m++)
{
if(frames[m] == -1)
{
frames[m] = pages[n];
b = 1;
page_fault++;
break;
}
}
}
if(b == 0)
{
for(m = 0; m < total_frames; m++)
{
temp[m] = 0;
}
for(k = n - 1, l = 1; l <= total_frames - 1; l++, k--)

Departmentof CSE ASTC


{
for(m = 0; m < total_frames; m++)
{
if(frames[m] == pages[k])
{
temp[m] = 1;
}
}
}
for(m = 0; m < total_frames; m++)
{
if(temp[m] == 0)
position = m;
}
frames[position] = pages[n];
page_fault++;
}
for(m = 0; m < total_frames; m++)
{
printf("%d\t", frames[m]);
}
printf("\n");
}
printf("\nTotal Number of Page Faults:\t%d\n", page_fault);

return 0;
}
Output –
1: 1 -1 -1
2: 1 2 -1
3: 1 2 3
2: 1 2 3
1: 1 2 3
5: 1 2 5
2: 1 2 5
1: 1 2 5
6: 1 2 6
2: 1 2 6
5: 5 2 6
6: 5 2 6
3: 5 3 6
1: 1 3 6
3: 1 3 6
6: 1 3 6
1: 1 3 6
2: 1 2 6
4: 1 2 4
3: 3 2 4
Total Number of Page Faults: 11

Departmentof CSE ASTC


c) LFU PAGE REPLACEMENT ALGORITHM

Source Code:

#include<stdio.h>
void print(int frameno,int frame[])
{
int j;
for(j=0;j<frameno;j++)
printf("%d\t",frame[j]);
printf("\n");
}
int main()
{
int i,j,k,n,page[50],frameno,frame[10],move=0,flag,count=0,count1[10]={0},
repindex,leastcount;
float rate;
printf("Enter the number of pages\n");
scanf("%d",&n);
printf("Enter the page reference numbers\n");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter the number of frames\n");
scanf("%d",&frameno);
for(i=0;i<frameno;i++)
frame[i]=-1;
printf("Page reference string\tFrames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t\t",page[i]);
flag=0;
for(j=0;j<frameno;j++)
{

Departmentof CSE ASTC


if(page[i]==frame[j])
{
flag=1;
count1[j]++;
printf("No replacement\n");
break;
}
}
if(flag==0&&count<frameno)
{
frame[move]=page[i];
count1[move]=1;
move=(move+1)%frameno;
count++;
print(frameno,frame);
}
else if(flag==0)
{
repindex=0;
leastcount=count1[0];
for(j=1;j<frameno;j++)
{
if(count1[j]<leastcount)
{
repindex=j;
leastcount=count1[j];
}
}

frame[repindex]=page[i];
count1[repindex]=1;
count++;

Departmentof CSE ASTC


print(frameno,frame);
}
}
rate=(float)count/(float)n;
printf("Number of page faults is %d\n",count);
printf("Fault rate is %f\n",rate);
return 0;
}
OUTPUT:
Enter the number of pages
4
Enter the page reference numbers
2
3
4
5
Enter the number of frames
4
Page reference string Frames
2 2 -1 -1 -1
3 2 3 -1 -1
4 2 3 4 -1
5 2 3 4 5
Number of page faults is 4
Fault rate is 1.000000

Departmentof CSE ASTC


EXPERIMENT : 10

AIM: Simulate Paging Technique of memory management.

Source Code:
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int size,m,n,pgno,pagetable[3]={5,6,7},i,j,frameno;
double m1;
int ra=0,ofs;
clrscr();
printf(“Enter process size (in KB of max 12KB):”); /*reading memeory size*/
scanf(“%d”,&size);
m1=size/4;
n=ceil(m1);
printf(“Total No. of pages: %d”,n);
printf(“\n Enter relative address (in hexadecimal notation eg.0XRA) \n”);
//printf(“The length of relative Address is : 16 bits \n\n The size of offset is :12 bits\n”);
scanf(“%d”,&ra);
pgno=ra/1000; /*calculating physical address*/
ofs=ra%1000;
printf(“page no=%d\n”,pgno);
printf(“page table”);
for(i=0;i<n;i++)
printf(“\n %d [%d]”,i,pagetable[i]);
frameno=pagetable[pgno];
printf(“\n Equivalent physical address : %d%d”,frameno,ofs);
getch();
}

Departmentof CSE ASTC


Output:
Enter the no of pages in memory: 2
Enter page size: 5
Enter no of frames: 3
Enter the page table
(Enter frame no as -1 if that page is not present in any frame)
Page no frame no
------- -------
0 2
1 5
Enter the logical address (i.e,page no & offset):4 150
Physical address(i.e,frame no & offset):0,150
Do you want to continue(1/0)?:1

Enter the logical address(i.e,page no & offset):2 250

Physical address(i.e,frame no & offset):6,250


Do you want to continue(1/0)?:

Departmentof CSE ASTC


EXPERIMENT : 11

AIM:. Implement Bankers Algorithm for Dead Lock avoidance and prevention

Source Code:
#include<stdio.h>

int main() {
/* array will store at most 5 process with 3 resoures if your process or
resources is greater than 5 and 3 then increase the size of array */
int p, c, count = 0, i, j, alc[5][3], max[5][3], need[5][3], safe[5], available[3], done[5],
terminate = 0;
printf("Enter the number of process and resources");
scanf("%d %d", & p, & c);
// p is process and c is diffrent resources
printf("enter allocation of resource of all process %dx%d matrix", p, c);
for (i = 0; i < p; i++) {
for (j = 0; j < c; j++) {
scanf("%d", & alc[i][j]);
}
}
printf("enter the max resource process required %dx%d matrix", p, c);
for (i = 0; i < p; i++) {
for (j = 0; j < c; j++) {
scanf("%d", & max[i][j]);
}
}
printf("enter the available resource");
for (i = 0; i < c; i++)
scanf("%d", & available[i]);

printf("\n need resources matrix are\n");


for (i = 0; i < p; i++) {
for (j = 0; j < c; j++) {
need[i][j] = max[i][j] - alc[i][j];
printf("%d\t", need[i][j]);
}
printf("\n");
}
/* once process execute variable done will stop them for again execution */
for (i = 0; i < p; i++) {
done[i] = 0;
}
while (count < p) {
for (i = 0; i < p; i++) {
if (done[i] == 0) {
for (j = 0; j < c; j++) {

Departmentof CSE ASTC


if (need[i][j] > available[j])
break;
}
//when need matrix is not greater then available matrix then if j==c will true
if (j == c) {
safe[count] = i;
done[i] = 1;
/* now process get execute release the resources and add them in available resources */
for (j = 0; j < c; j++) {
available[j] += alc[i][j];
}
count++;
terminate = 0;
} else {
terminate++;
}
}
}
if (terminate == (p - 1)) {
printf("safe sequence does not exist");
break;
}

}
if (terminate != (p - 1)) {
printf("\n available resource after completion\n");
for (i = 0; i < c; i++) {
printf("%d\t", available[i]);
}
printf("\n safe sequence are\n");
for (i = 0; i < p; i++) {
printf("p%d\t", safe[i]);
}
}

return 0;
}

Departmentof CSE ASTC


OUTPUT:

Enter the number of process and resources


33
enter allocation of resource of all process 3x3 matrix
210
213
451
enter the max resource process required 3x3 matrix
123
053
154
enter the available resource 20 3 420 3 4

need resources matrix are


-1 1 3
-2 4 0
-3 0 3

available resource after completion


28 10 8
safe sequence are
p0 p1 p2

Departmentof CSE ASTC


EXPERIMENT : 12

Aim: Simulate the following file allocation strategies

a) Sequential

b) Indexed

c) Linked

Source code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DISK_SIZE 10 // Size of the disk (number of blocks)

// Function to display the current disk state


void displayDisk(char disk[], int disk_size) {
printf("Disk state:\n");
for (int i = 0; i < disk_size; i++) {
printf("Block %d: %c\n", i, disk[i] ? disk[i] : ' ');
}
printf("\n");
}

// Sequential Allocation
void sequentialAllocation(char disk[], int disk_size, char file, int file_size) {
int start_block = -1;

// Find contiguous free blocks


for (int i = 0; i < disk_size - file_size + 1; i++) {
int can_allocate = 1;
for (int j = 0; j < file_size; j++) {
if (disk[i + j] != 0) {
can_allocate = 0;
break;
}
}

if (can_allocate) {
start_block = i;
break;
}
}

Departmentof CSE ASTC


// If contiguous blocks are found, allocate them to the file
if (start_block != -1) {
for (int i = 0; i < file_size; i++) {
disk[start_block + i] = file;
}
printf("File %c allocated sequentially at blocks: ", file);
for (int i = 0; i < file_size; i++) {
printf("%d ", start_block + i);
}
printf("\n");
} else {
printf("Error: Not enough contiguous blocks available for file %c.\n", file);
}
}

// Indexed Allocation
void indexedAllocation(char disk[], int disk_size, char file, int file_size) {
int index_block = -1;

// Find space for the index block


for (int i = 0; i < disk_size; i++) {
if (disk[i] == 0) {
index_block = i;
break;
}
}

// If no space for index block, print an error


if (index_block == -1) {
printf("Error: Not enough space for index block for file %c.\n", file);
return;
}

// Find blocks for the file


int allocated_blocks[file_size];
int block_count = 0;
for (int i = 0; i < disk_size; i++) {
if (disk[i] == 0) {
disk[i] = file;
allocated_blocks[block_count++] = i;
if (block_count == file_size) break;
}
}

// If sufficient blocks are found, store the index block


if (block_count == file_size) {
disk[index_block] = 'I'; // Mark as an index block
printf("File %c allocated with index block %d at blocks: ", file, index_block);

Departmentof CSE ASTC


for (int i = 0; i < block_count; i++) {
printf("%d ", allocated_blocks[i]);
}
printf("\n");
} else {
printf("Error: Not enough free blocks for file %c.\n", file);
}
}

// Linked Allocation
void linkedAllocation(char disk[], int disk_size, char file, int file_size) {
int last_block = -1;
int allocated_blocks[file_size];

// Find free blocks and link them


int block_count = 0;
for (int i = 0; i < disk_size; i++) {
if (disk[i] == 0) {
disk[i] = file;
allocated_blocks[block_count++] = i;
if (block_count == file_size) break;
}
}

// If enough blocks are found, link them


if (block_count == file_size) {
for (int i = 0; i < block_count - 1; i++) {
disk[allocated_blocks[i]] = allocated_blocks[i + 1]; // Link current block to next
}
disk[allocated_blocks[block_count - 1]] = -1; // Last block points to -1 (NULL)
printf("File %c allocated with linked blocks: ", file);
for (int i = 0; i < block_count; i++) {
printf("%d ", allocated_blocks[i]);
}
printf("\n");
} else {
printf("Error: Not enough free blocks for file %c.\n", file);
}
}

int main() {
char disk[DISK_SIZE] = {0}; // 0 indicates free block, non-zero values are allocated blocks
char file;
int file_size;

// Sequential Allocation
printf("Sequential Allocation:\n");
sequentialAllocation(disk, DISK_SIZE, 'A', 3);

Departmentof CSE ASTC


displayDisk(disk, DISK_SIZE);

// Indexed Allocation
printf("Indexed Allocation:\n");
indexedAllocation(disk, DISK_SIZE, 'B', 2);
displayDisk(disk, DISK_SIZE);

// Linked Allocation
printf("Linked Allocation:\n");
linkedAllocation(disk, DISK_SIZE, 'C', 4);
displayDisk(disk, DISK_SIZE);
IZE);

return 0;
}

OUTPUT:

You might also like