0% found this document useful (0 votes)
7 views79 pages

Os Lab Manual

The document is a laboratory manual for the Operating Systems Lab (CS2108) at Sanketika Vidya Parishad Engineering College, outlining the vision, mission, and educational objectives of the Computer Science and Engineering department. It includes course objectives, outcomes, and detailed instructions for lab sessions, as well as a syllabus covering topics such as UNIX/Linux commands, process scheduling, and resource management. Additionally, it provides guidelines for laboratory conduct and a list of references for further reading.

Uploaded by

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

Os Lab Manual

The document is a laboratory manual for the Operating Systems Lab (CS2108) at Sanketika Vidya Parishad Engineering College, outlining the vision, mission, and educational objectives of the Computer Science and Engineering department. It includes course objectives, outcomes, and detailed instructions for lab sessions, as well as a syllabus covering topics such as UNIX/Linux commands, process scheduling, and resource management. Additionally, it provides guidelines for laboratory conduct and a list of references for further reading.

Uploaded by

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

OPERATING SYSTEMS LAB

(CS2108) LABORATORY MANUAL & RECORD

B. Tech (CSE) (With effect from 2022-23 admitted batches)


(II YEAR- ISEM)

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE


(APPROVED BY AICTE, AFFILIARED TO ANDHRA
UNIVERSITY, ACCREDITED BY NAAC-A GRADE, ISO
9001:2015 CERFIFIED) PM PALEM,
VISAKHAPATNAM-41,
www.svpce.edu.in

1
INSTITUTE VISION AND MISSION

VISION

To be a premier institute of knowledge of share quality research and development technologies


towards national buildings

MISSION

 Develop the state of the art environment of high quality of learning


 Collaborate with industries and academic towards training research innovation and
entrepreneurship
 Create a platform of active participation co-circular and extra- circular activities

DEPARTMENT VISION AND MISSION

VISION

To impart quality education for producing highly talented globally recognizable techno carts
and entrepreneurs with innovative ideas in computer science and engineering to meet industrial
needs and societal expectations

MISSION

 To impart high standard value-based technical education in all aspects of Computer


Science and Engineering through the state of the art infrastructure and innovative
approach.
 To produce ethical, motivated, and skilled engineers through theoretical knowledge
and practical applications.
 To impart the ability for tackling simple to complex problems individually as well as
in a team.
 To develop globally competent engineers with strong foundations, capable of “out of
the box” thinking so as to adapt to the rapidly changing scenarios requiring socially
conscious green computing solutions.

2
PROGRAM EDUCATIONAL OBJECTIVES (PEOs)
Graduates of B. Tech in computer science and Engineering Program shall be able to
PEO1: Strong foundation of knowledge and skills in the field of Computer Science and
Engineering.
PEO2: Pr ovide solutions to challenging problems in their profession by applying computer
engineering theory and practices.
PEO3: Produce leadership and are effective in multidisciplinary environment.

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO1: Ability to design and develop computer programs and understand the structure and
development methodologies of software systems.
PSO2: Ability to apply their skills in the field of networking, web design, cloud computing
and data analytics.
PSO3: Ability to understand the basic and advanced computing technologies towards getting
employed or to become an entrepreneur

3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

PROGRAM OUTCOMES
1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem Analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. Design/Development of Solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct Investigations of Complex Problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern Tool Usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex engineering
activities with an understanding of the limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and Sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, give and receive clear
instructions.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 4


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

11. Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments
12. Life-Long Learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 5


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COURSE OBJECTIVES
• To learn about UNIX/LINUX operating system environment.
• To learn about system calls for UNIX/LINUX Operating System.
• To understand resource management policies and mechanisms and their performance evaluation.
• To study and implement various mechanisms used for managing processes, including process
creation, process scheduling, and inter-process communication (IPC) via system calls.
• To provide students with a hands-on understanding of key OS concepts such as scheduling
algorithms, page replacement, deadlock management, disk scheduling, and memory
management.

COURSE OUTCOMES (CO)

• The student learns about multiprogramming, and multitasking capabilities of UNIX/LINUX.

• The student develops skill in writing C programs using system calls for process management,
inter process communication and other aspects.

• The student learns to simulate OS resource management aspects like process scheduling, page
replacement, disk scheduling, free space management and others to evaluate performance.

• Develop programs that simulate OS process scheduling algorithms, including FCFS (First-
Come, First-Served), SJF (Shortest Job First), and Round Robin.
• Write C programs to simulate free space management techniques, allowing students to
understand how the OS handles free memory or disk space.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 6


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),
those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:

a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
c. Proper Dress code and Identity card.

4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note
book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which should
be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab
after completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept
properly

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 7


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS2108 OPERATING SYSTEMS LAB SYLLABUS

MODULE1
1. OS lab familiarization, Home Assignment on Unix commands, Vi editor
2. Simple shell programming exercises
3. Shell programming using decision making constructs, loop
constructs, file and directory manipulation
4. Simple C programs using command line arguments, system calls,
library function calls, make utility
5. C programs using system call to create processes and study parent,
child process mechanism
6. C programs to create process chaining, spawning
7. C programs to error handling using errno(), perror() function
8. C programs to use pipe system call for inter process communication

MODULE II

1. C programs to study process scheduling implementing FCFS,


Shortest Job First, and Round Robin algorithms

2. C programs to study page replacement implementing FIFO,


Optimal, and LRU page replacement algorithms

3. C programs to study deadlock avoidance and detection

4. C Programs to simulate free space management (first fit, best fit, worst fit).

5. C programs to study disk scheduling algorithms (i.e., SCAN, SSTF, LOOK,


etc.,)

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 8


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

References:

1. Unix concepts and applications by Sumitabha Das, TMH Publications.


2. Unix programming by Stevens, Pearson Education.
3. Shell programming by Yashwanth Kanetkar.
4. Operating System Concepts by Silberschatz, and Peter Galvin.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 9


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

TABLE OF CONTENTS
SNO CONTENT PAGE NO

MODULE -1
OS Introduction
1. 14-19
OS lab familiarization, Home Assignment on Unix commands,
Vi editor

2. 20-23
Simple shell programming exercises

3. 24-30
Shell programming using decision making
constructs, loop constructs, file and
directory manipulation

4 Simple C programs using command line arguments, 31-34


system calls, library function calls, make utility
5 35-36
C programs using system call to create processes
and study parent, child process mechanism
6 37-42
C programs to create process chaining, spawning
7 43-44
C programs to error handling using errno(), perror() function
8 45-46
C programs to use pipe system call for inter process
communication

MODULE-2

C programs to study process scheduling


1 47-54
implementing FCFS, Shortest Job First, and
Round Robin algorithms

2 55-56
C programs to study page replacement
implementing FIFO, Optimal, and LRU page
replacement algorithms.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 10


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
3 67-72
C programs to study deadlock avoidance and detection.

4 73-81
C Programs to simulate free space management (first fit, best fit,
worst fit).

5 82-87
C programs to study disk scheduling algorithms (i.e., SCAN,
SSTF, LOOK, etc.,)

88-91
Viva Questions

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 11


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

OPERATING SYSTEM
Introduction : A computer system can be divided into four components
. Hardware
. Operating system
. System programs word processor spreadsheets, Accounting software.
. Application programs.
In 1960s definition of an operating system is software. Is software that controls the hardware. However, today
due to microcode, we need a better definition on. On we see an operating system as the program that make a
hardware use. In brief on operating system is the set of programs that controls the computer .
An operating system is software that creates a relation between the user software and hardware. So it is an
interface between. The all the computers need baskets. Software known as operating system to function.
The os acts as an interface between the user application programs, hardware and the system peripherals. The
os acts as in the first software to be loaded when a computer starts up. The entire application programs are
loaded after the os.
Types of operating system :
. Single user : If the single user operating system is loaded in computers memory The computer would be
able to handle one user at a time .
. Multi user. : If the multi user operating system is loaded in computers memory, the. Computer would be able
to handle more than one user at a time.
. Network.:If the network operating system is loaded in computers memory, the computer. Would be able to
handle more than one computer at a time.
Command prompt interface:
Operating system provides a text based interface called common prompt from the Command prompt.
Command can be. Issued to perform file and disk management end to run programs. Result of these commands
are presented to the users as text messages.
C: \> -
The command prompt can be an alphabet followed by one: one.> and one blinking element called cursor.
Microsoft Windows XP version (5.1. .2600)
(c) Copyright 1985 to 2001 Microsoft Corp.
C: \00 Comments and settings \ Rana Shankar)c : \
C: \ He is not recognized as an internal or external command. Separable program or batch file.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 12


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING
C : \ Documents and settings \ Rana Shankar, > e:
C : \ Documents and settings \ Rana Shankar, > cd \
C:\>
C: \>_
Where c : Represents a drive letter
\ Represent the current folder or directory
\e Represent the end of the prompt and
_ blinking element( represents the cursor.)
What are the basic comments of ubuntu?
This section contains some basic comments of Ubuntu, so let us start and discuss them one by 1. Firstly, you
must open the terminal in Ubuntu. Press control + alt +T from your keyboard to open the terminal.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 13


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

MODULE-1
1. OS LAB FAMILIARIZATION, HOME ASSIGNMENT ON UNIX COMMANDS, VI
EDITOR
1. Command 1 : PWD
This command refers to the present working directory in which you are operating. In simpler
words, in which your terminal is open to check PWD, execute the PWD keyboard in your
terminal and hit enter the command of PWD is written below along with the result of that
command.

Eg : Adnan @ adnan : { pwd

/home/adnan

2. Command 2 : dir
This DIR Command is used to print all the available directories in the present working
directory.

Eg : adnan @adnan : $dir

A top downloads music, public videos, document file, text, pictures, templates

Adnan @ adnan : $

3. Command 3 : ls
This command is used to list down all the directories in files inside the present working
directory. This command. Can be executed as shown below.

Eg : adnan @ adnan : $ls

Desktop, downloads ,music, public videos, documents ,file text pictures, templates.

This ls command supports various flags. And each flag has same specific role in printing the
directories or files of the current working directory.

To print the detail information of the files or directories, the -al flag is used with the LS
command.

Adnan @ adnan : $ls – al

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 14


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

Total 100

Drwxr – xr – 16 Adnan Adnan 4096 August 12 11:35

-rw ________ adnanadnan 4096 aug 11 9: 52

The R flag will print subdirectories of a directory as well

Adnan @ adnan : ls. R

Desktop, downloads, music ,public videos ,download file text, pictures, templates.

./ Desktop

./ Documents.

./ Downloads.

./ Music.

./ Pictures.

Screenshot from 2021 8-12 to 14- 51-24

./ Public.

./ Templates.

./ Videos.

Adnan @ adnan : $

4. Command 4 : cd
One of the most used comments of Ubuntu. You can change the directories in the terminal
using the cd command. For instance, the following command will change the pwd to desktop.

Adnan @ adnan : $ls

Desktop downloads music publicvideos documents. Pictures templates.

Adnan @ adnan :$ cd desktop

There are multiple uses of this command. One of can change the present directory to root
directory on home directory using this command. When you open a fresh terminal, you are in
the home directory.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 15


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

5. Command 5 : touch
This Ubuntu command can be used to create a new file as well as one can use it to change the
time lamp of any file the command given below will create a new text time in Pwd.

Adnan @ adnan : $touch file .txt

Adnan @ adnan : $ ls

Desktop, downloads ,music, public videos, documents, Pictures ,templates.

Adnan @ adnan : $

6. Command 6 : Cat
This command is used to show the content of any file. For instance, the following command
will display the content inside file.text.

Adnan @ adnan :$ cat file /.txt

Ford escape s – 24885.

Ford escape se -26610.

Ford escapesel -29205.

Adnan @ adnan : $

7. Command 7 :mkdir
The above mentioned command will take a directory in your pwd. For example, the following
command will make directory new in Pwd.

Adnan @ adnan : $ mkdir new

Adnan @ adnan : $ls

Desktops , downloads, file text ,new ,pictures ,documents file text, music

Adnan @ adnan : $

8. Command 8 : rm
This remove command is used to remove the specific files from a directory. For instance, below
mentioned command would remove the test text file from the pwd.

Adnan @ adnan : $ls

Desktop , downloads, file text, pictures, templates, downloads, music ,public text.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 16
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

Are you can remove the empty directory as the command given to remove the test directory.

9. Command 9 : cp
The CP Command will help you to copy any file on folder to any directory

to copy a file directory 1 :

adnan @ adnan : $ ls directory

10 .Command 10 : mv

You can use this command to move files around the computer, and you can also rename files
or directories inside a specific directory. The command given below will not the file 2.text to
directory.

Adnan @ adnan : $mv file2.txt directory

STUDY OF VI EDITOR :

VI editor : The VI editor visual editor is screen editor, which is available on almost all unit
systems. Vi has no means, but instead uses the combination of keystrokes in order to
accomplish the commands.

Models of VI editor :

There are three different models in vi editor :

Command mode

text mode or input mode

ex mode or last line mode.

Commands :

I : Insert text before the current characters.

I : Insert text at the beginning of the current file.

A : Appends text after the current character.

A : Appends text at the line end of the current line.

R : Replaces the current character at the new one.


SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 17
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

R: Replaces a set of characters with the new set of characters.

S : Subsidies the current line with the supply test.

Deleting or cutting characters words and lines :

To delete a character first place your cursor on that character.

Y: They lose the character under the cursor.

X : Deletes the character to the left of your cursor.

Dd : Deletes all the current line.

Command text object

D (delete) v( word to the left)

Y (yonk\copy)

B (Go to the right or back )

C (change)

E (end of word)

A (top of screen )

M (middle of screen)

O (zero first character or a line)

$ (end of line)

Screen movement :

Remove the cursor to a line within your current screen.

Uses the following keys :

M moves the cursor to the top of the line of the screen.

M moves the cursor to the middle line of the screen .

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 18


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

To scroll through the file and see other screens are :

Ctrl-F scrolls down one screen

Ctrl -b scrolls up one screen

Ctrl-r scrolls up a half a screen .

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 19


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

2. SIMPLE SHELL PROGRAMMING EXERCISES

1. Hello, World! Script

Write a shell script that prints "Hello, World!" to the console

#!/bin/bash
echo "Hello, World!"

OUTPUT:

2. Simple Calculator

Create a script that takes two numbers as input and performs basic arithmetic operations (add,
subtract, multiply, divide)

#!/bin/bash
echo"Enter first number:"
read num1
echo"Enter second number:"
read num2
echo"Choose operation (+, -, *, /):"
read op
case$opin
+) echo"Result: $((num1 + num2))" ;;
-)echo"Result: $((num1 - num2))" ;;
*) echo"Invalid operator" ;;
esac

OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 20


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

3. Check Even or Odd

Write a script that checks if a number entered by the user is even or odd

#!/bin/bash
echo"Enter a number:"
read num
if ((num % 2 == 0)); then
echo"$num is Even"
else
echo"$num is Odd"
fi

OUTPUT:

4. File Exists or Not

Create a script that checks if a file exists in the current directory

#!/bin/bash
echo"Enter filename:"
read filename
if [ -e "$filename" ]; then
echo"File exists."
else
echo"File does not exist."
fi

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 21


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

OUTPUT

5. Display Numbers from 1 to 10

Write a script to print numbers from 1 to 10 using a loop.

#!/bin/bash
for i in {1..10}; do
echo$i
done

OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 22


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

3. SHELL PROGRAMMING USING DECISION MAKING


CONSTRUCTS, LOOP CONSTRUCTS, FILE AND DIRECTORY
MANIPULATION

1. using if to check a condition

Using if

#!/bin/bash
echo"Enter a number:"
read num
if [ $num -gt 0 ]; then
echo"The number is positive."
fi
OUTPUT:

2. Check If a Number Is Positive or Negative

Using if- else

#!/bin/bash
echo"Enter a number:"
read num
if [ $num -gt 0 ]; then
echo"The number is positive."
else
echo"The number is negative or zero."
fi
OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 23


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

OUTPUT:

2. Loop Constructs:
1. for loop
#!/bin/bash
for i in {1..10}
do
echo "Number: $i"
done
OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 24


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

2. while loop:
#!/bin/bash
i=1
while [$i -le 7 ]
do
echo "Number: $i"
((i++))
Done
OUTPUT:

3. Do while:
#!/bin/bash
# Mimicking the 'do-while' loop behavior in Shell
valid=false
# Using while loop to mimic the do-while loop
while [ "$valid" == false ]; do
echo "Please enter a positive number:”
read num
# Check if the number is positive
if [ "$num" -gt 0 ]; then

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 25


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

echo "You entered a valid number: $num"


valid=true # Set to true to break the loop
else
echo "The number is not positive. Please try again."
fi
Done
OUTPUT:

Files and directories:


1. Create a directory:
#! /bin/bash
echo “enter directory name to create:”
read dirname
mkdir “$dirname”
echo “Directory $dirname created.”
OUTPUT:

2. Remove a Directory
#!/bin/bash
Echo “enter directory name to remove:”
eead diname
rmdir “$dirname”

echo “Directory $diname removed.”


OUTPUT:

3. creating a file
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 26
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

#!/bin/bash
echo “enter the file name to create:”
read filename
touch “$filename”

echo “file ‘$filename’ created successfully.”


OUTPUT:

4. Writing to a file:
#!/bin/bash
echo “Enter the file name:”
read filename
echo “Enter the text to write to the file:”
read text
echo “$text” > “$filename”
echo “Content written to ‘$filename’.”
OUTPUT:

5. Reading from a file:


#!/bin/bash
echo “Enter the file name:”
read filename
echo “Enter the text to write to the file:”
read text
echo “$text” > “$filename”
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 27
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

echo “Content written to ‘$filename’.”


Output:

6. Deleting a file:
#!/bin/bash
echo “Enter the filename to delete:”
read filename
if[-f “$filename”]; then
rm “$filename”
echo “File ‘$filename’ has been deleted.”
else
echo “File ‘$filename’ does not exist.”
fi
Output:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 28


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

4. SIMPLE C PROGRAMS USING COMMAND LINE


ARGUMENTS,SYSTEM CALLS,LIBRARY FUNCTIONS CALLS,MAKE
UTILITY:
1. Command line arguments:
#include<stdio.h>
int main()
{
char *argv[]={"program","arg1","arg2","arg3"};
int argc=4;
int i;
printf("Number of arguments:%d\n",argc-1);
printf("Arguments provided:\n");
for(i=1;i<argc;i++)
{
printf("Argument %d:%s\n",i,argv[i]);
}
return 0;
}
OUTPUT:

2. System calls :

#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
int main()
{
int pid = fork();
if(pid == 0) {
printf(“Child process\n”);

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 29


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

printf(“Child process ID: %d\n”, getpid());


printf(“Parent process ID: %d\n”, getppid());
}
else {
printf(“Parent process\n”);
printf(“Parent process ID: %d\n”, getpid());
printf(“Child process ID: %d\n”, pid);
wait(NULL);
}
return 0;
}
OUTPUT:

3. Library function calls :


#include<stdio.h>

int main() {

FILE *file;

char data[] = "Hello this is a sample text for file operations in c.";

// Open the file in write mode

file = fopen("sample.txt", "w");

if (file == NULL) {

perror("Error opening file");

return 1;

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 30


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

// Write data to the file

fwrite(data, sizeof(char), sizeof(data) - 1, file);

printf("Data written to file successfully.\n");

// Close the file

fclose(file);

// Open the file in read mode

file = fopen("sample.txt", "r");

if (file == NULL) {

perror("Error opening file");

return 1;

// Read data from the file

char buffer[100];

fread(buffer, sizeof(char), sizeof(buffer) - 1, file);

// Null-terminate the buffer to ensure proper string formatting

buffer[sizeof(buffer) - 1] = '\0';

// Print the data read from the file

printf("Data read from file: %s\n", buffer);

// Close the file

fclose(file);

return 0;

OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 31


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

5. C PROGRAMS USING SYSTEM CALLS TO CREATE PROCESSES


AND STUDY PARENT,CHILD PROCESS MECHANISM:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
int main() {
pid_t pid; //variable to hold the procedd ID
//create a new process using fork()
pid = fork();
if(pid<0){
//Error occured in forking
perror("Fork failed");
exit(1);
}
//If pid==0,we are in the child process
if(pid==0){
printf("Child Process:\n");
printf(" -PID of child: %d\n", getpid()); //Child's process ID
printf(" -PID of parent: %d\n", getppid()); //Parent's process ID
printf(" -Child process executed\n");
}
//If pid>0,we are in the parent process
else{
printf("Parent process:\n");
printf(" -PID of parent:%d\n", getpid()); //Parent's process ID
printf(" -PID of child:%d\n", pid); //Child's process ID (returned by fork)
printf(" -Parent process executed\n");
}
//Both processes will continue execution from here
printf("Both parent and child processes contine to execute independently\n");
return 0;

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 32


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

}
OUTPUT:-

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 33


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

6. C PROGRAMS TO CREATE PROCESS CHAINING, SPAWNING:

1. Chaining:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main() {
int pipe1[2], pipe2[2];
pid_t pid1, pid2, pid3;

// Create first pipe


if (pipe(pipe1) == -1) {
perror("pipe1");
exit(1);
}

// Create second pipe


if (pipe(pipe2) == -1) {
perror("pipe2");
exit(1);
}

// First process: Generate numbers (1 to 10)


if ((pid1 = fork()) == 0) {
close(pipe1[0]);
close(pipe2[0]);
close(pipe2[1]);

for (int i = 1; i <= 10; i++) {


write(pipe1[1], &i, sizeof(int));

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 34


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

}
close(pipe1[1]);
exit(0);
}

// Second process: Filter even numbers


if ((pid2 = fork()) == 0) {
close(pipe1[1]);
close(pipe2[0]);

int num;
while (read(pipe1[0], &num, sizeof(int)) > 0) {
if (num % 2 == 0) {
write(pipe2[1], &num, sizeof(int));
}
}
close(pipe1[0]);
close(pipe2[1]);
exit(0);
}

// Third process: Print even numbers


if ((pid3 = fork()) == 0) {
close(pipe1[0]);
close(pipe1[1]);
close(pipe2[1]);

int num;
while (read(pipe2[0], &num, sizeof(int)) > 0) {
printf("Even number: %d\n", num);
}
close(pipe2[0]);

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 35


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

exit(0);
}

// Parent process: Wait for all child processes to finish


close(pipe1[0]);
close(pipe1[1]);
close(pipe2[0]);
close(pipe2[1]);
wait(NULL);
wait(NULL);
wait(NULL);

return 0;
}
Output:

2. Spawing:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t pid;

// Create a child process using fork()


pid = fork();

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 36


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

if (pid == -1) {
// If fork fails
perror("fork failed");
exit(1);
}

if (pid == 0) {
// Child process code
printf("Child process: Executing 'ls' command\n");

// Execute a new program (replace the child process with "ls")


execlp("ls", "ls", "-l", NULL); // -l flag lists files with details

// If execlp fails
perror("execlp failed");
exit(1);
} else {
// Parent process code
printf("Parent process: Waiting for child to finish...\n");

// Wait for the child process to complete


wait(NULL);

printf("Parent process: Child finished execution\n");


}

return 0;
}
Output:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 37


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 38


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

7. C PROGRAMS TO ERROR HANDLING USING ERRNO(), PERROR()


FUNCTION:
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
// Try to open a non-existent file
FILE *file = fopen("non_existent_file.txt", "r");
if (file == NULL) {
// If the file open failed, errno is set
// Print the error using perror()
perror("Error opening file");
// Alternatively, you can use strerror() to print a more readable error message
printf("Error code using strerror: %s\n", strerror(errno));

// You can also print the actual error number (errno)


printf("Error number: %d\n", errno);
} else {
// If file opens successfully, close it
fclose(file);
}
return 0;
}

Output:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 39


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

8. C PROGRAMS TO USE PIPE SYSTEM CALL FOR INTER PROCESS


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

int main() {
int pipefd[2];
pid_t pid;

if (pipe(pipefd) == -1) {
perror("pipe failed");
return 1;
}

pid = fork();

if (pid < 0) {
perror("fork failed");
return 1;
}

if (pid > 0) {
// Parent process: runs "ls"
close(pipefd[0]); // Close unused read end
dup2(pipefd[1], STDOUT_FILENO); // Redirect stdout to pipe write end
close(pipefd[1]);

execlp("ls", "ls", NULL); // Execute ls command


perror("execlp failed");
} else {
// Child process: runs "grep .c"
close(pipefd[1]); // Close unused write end

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 40


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

dup2(pipefd[0], STDIN_FILENO); // Redirect stdin to pipe read end


close(pipefd[0]);

execlp("grep", "grep", ".c", NULL); // Execute grep command


perror("execlp failed");
}

return 0;
}

OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 41


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

MODULE 2
1. C PROGRAMS TO STUDY PROCESS SCHEDULING
IMPLEMENTING FCFS,SHORTEST JOB FIRST, AND ROUND ROBIN
ALGORITHMS:
1. FCFS: (program-1):
#include<stdio.h>
int main()
{
int AT[10],BT[10],WT[10],TT[10],n;
int burst=0,cmpl_T;
float Avg_WT,Avg_TT,Total=0;
printf("Enter number of the process\n");
scanf("%d",&n);
printf("Enter Arrival time and Burst time of the process\n");
printf("AT\tBT\n");
for(int i=0;i<n;i++)
{
scanf("%d%d",&AT[i],&BT[i]);
}
// Logic for calculating Waiting time
for(int i=0;i<n;i++)
{
if(i==0)
WT[i]=AT[i];
else
WT[i]=burst-AT[i];
burst+=BT[i];
Total+=WT[i];
}
Avg_WT=Total/n;
// Logic for calculating Turn around time
cmpl_T=0;

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 42


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

Total=0;
for(int i=0;i<n;i++)
{
cmpl_T+=BT[i];
TT[i]=cmpl_T-AT[i];
Total+=TT[i];
}
Avg_TT=Total/n;
// printing of outputs
printf("Process ,Waiting_time ,TurnA_time\n");
for(int i=0;i<n;i++)
{
printf("%d\t\t%d\t\t%d\n",i+1,WT[i],TT[i]);
}
printf("Average waiting time is : %f\n",Avg_WT);
printf("Average turn around time is : %f\n",Avg_TT);
return 0;
}
OUTPUT:

2. SJF: (program-2):
#include<stdio.h>
#include<string.h>
void main()

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 43


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

{
int et[20],at[10],n,i,j,temp,st[10],ft[10],wt[10],ta[10];
int totwt=0,totta=0;
float awt,ata;
char pn[10][10],t[10];
//clrscr();
printf("Enter the number of process:");
scanf("%d",&n);
for(i=0; i<n; i++)
{
printf("Enter process name, arrival time& execution time:");
//flushall();
scanf("%s%d%d",pn[i],&at[i],&et[i]);
}
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(et[i]<et[j])
{
temp=at[i];
at[i]=at[j];
at[j]=temp;
temp=et[i];
et[i]=et[j];
et[j]=temp;
strcpy(t,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],t);
}
}
for(i=0; i<n; i++)
{

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 44


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

if(i==0)
st[i]=at[i];
else
st[i]=ft[i-1];
wt[i]=st[i]-at[i];
ft[i]=st[i]+et[i];
ta[i]=ft[i]-at[i];
totwt+=wt[i];
totta+=ta[i];
}
awt=(float)totwt/n;
ata=(float)totta/n;
printf("\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime");
for(i=0; i<n; i++)
printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],wt[i],ta[i]);
printf("\nAverage waiting time is:%f",awt);
printf("\nAverage turnaroundtime is:%f",ata);
}
OUTPUT:

3. Round robin: (program-3):


#include<stdio.h>
int main()
{
int count,j,n,time,remain,flag=0,time_quantum;
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 45
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=time_quantum;
time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count]);
wait_time+=time-at[count]-bt[count];

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 46


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

turnaround_time+=time-at[count];
flag=0;
}
if(count==n-1)
count=0;
else if(at[count+1]<=time)
count++;
else
count=0;
}
printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);
printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);
return 0;
}
OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 47


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

2. C PROGRAMS TO STUDY PAGE REPLACEMENT IMPLEMENTING


FIFO, OPTIMAL, AND LRU PAGE REPLACEMENT ALGORITHMS:
1. FIFO
#include <stdio.h>
int main()
{
int referenceString[10], pageFaults = 0, m, n, s, pages, frames;
printf("\nEnter the number of Pages:\t");
scanf("%d", &pages);
printf("\nEnter reference string values:\n");
for(m= 0; m < pages; m++)
{
printf("Value No. [%d]:\t", m + 1);
scanf("%d", &referenceString[m]);
}
printf("\n What are the total number of frames:\t");
{
scanf("%d", &frames);
}
int temp[frames];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(referenceString[m] == temp[n])
{
s++;

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 48


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

pageFaults--;
}
}
pageFaults++;
if((pageFaults <= frames) && (s == 0))
{
temp[m] = referenceString[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = referenceString[m];
}
printf("\n");
for(n = 0; n < frames; n++)
{
printf("%d\t", temp[n]);
}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults);
return 0;
}
OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 49


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

2. Optimal page replacement


#include<stdio.h>
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1, flag2, flag3, i, j, k,
pos, max, faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);
printf("Enter number of pages: ");
scanf("%d", &no_of_pages);
printf("Enter page reference string: ");
for(i = 0; i < no_of_pages; ++i){
scanf("%d", &pages[i]);
}
for(i = 0; i < no_of_frames; ++i){
frames[i] = -1;
}
for(i = 0; i < no_of_pages; ++i){
flag1 = flag2 = 0;
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == pages[i]){
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 50
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

flag1 = flag2 = 1;
break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){
if(frames[j] == -1){
faults++;
frames[j] = pages[i];
flag2 = 1;
break;
}
}
}

if(flag2 == 0){
flag3 =0;

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


temp[j] = -1;

for(k = i + 1; k < no_of_pages; ++k){


if(frames[j] == pages[k]){
temp[j] = k;
break;
}
}
}

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


if(temp[j] == -1){

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 51


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

pos = j;
flag3 = 1;

break;
}
}

if(flag3 ==0){
max = temp[0];
pos = 0;

for(j = 1; j < no_of_frames; ++j){


if(temp[j] > max){
max = temp[j];
pos = j;
}
}
}
frames[pos] = pages[i];
faults++;
}
printf("\n");
for(j = 0; j < no_of_frames; ++j){
printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);
printf("\n\nTotal Page Hits = %d", no_of_pages-faults);
return 0;
}

OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 52


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

3. LRU Page Replacement:


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

#define MAX_FRAMES 10

// Function to check if a page is in memory


int isPageInMemory(int page, int frames[], int numFrames) {
for (int i = 0; i < numFrames; i++) {
if (frames[i] == page) {
return 1; // Page is in memory
}
}
return 0; // Page is not in memory
}

// Function to find the least recently used (LRU) page


int findLRU(int time[], int numFrames) {
int min = 0;
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 53
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

for (int i = 1; i < numFrames; i++) {


if (time[i] < time[min]) {
min = i;
}
}
return min;
}

// Function to simulate the LRU page replacement algorithm


void LRUPageReplacement(int pageReferences[], int numPages, int numFrames)
{
int frames[numFrames];
int time[numFrames]; // To keep track of the last accessed time of pages
int pageFaults = 0;

// Initialize frames and time arrays


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

// Process the pages


for (int i = 0; i < numPages; i++) {
int page = pageReferences[i];

if (isPageInMemory(page, frames, numFrames)) {


// If page is already in memory, update the time
for (int j = 0; j < numFrames; j++) {
if (frames[j] == page) {

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 54


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

time[j] = i;
break;
}
}
} else {
// If page is not in memory, find the LRU page to replace
int lruIndex = findLRU(time, numFrames);
frames[lruIndex] = page;
time[lruIndex] = i;
pageFaults++;
}

// Print the current state of frames


printf("After processing page %d: ", page);
for (int j = 0; j < numFrames; j++) {
if (frames[j] != -1)
printf("%d ", frames[j]);
}
printf("\n");
}

// Print the total number of page faults


printf("Total Page Faults: %d\n", pageFaults);
}

int main() {
int numFrames, numPages;

// Input number of frames and pages


SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 55
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

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


scanf("%d", &numFrames);

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


scanf("%d", &numPages);

int pageReferences[numPages];

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


for (int i = 0; i < numPages; i++) {
scanf("%d", &pageReferences[i]);
}

// Simulate LRU page replacement


LRUPageReplacement(pageReferences, numPages, numFrames);

return 0;
}
OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 56


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 57


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

3. C PROGRAMS TO STUDY DEADLOCK AVOIDANCE AND


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

#define P 5 // Number of processes


#define R 3 // Number of resources

int allocation[P][R], max[P][R], need[P][R], available[R];

// Function to calculate the 'Need' matrix


void calculateNeed() {
for (int i = 0; i < P; i++) {
for (int j = 0; j < R; j++) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
}

// Function to check if the system is in a safe state (Banker's Algorithm)


int isSafe() {
int work[R], finish[P], safeSeq[P], count = 0;

// Initialize work and finish


for (int i = 0; i < R; i++) {
work[i] = available[i];
}

for (int i = 0; i < P; i++) {


finish[i] = 0; // Not finished
}

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 58


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

// Try to find a safe sequence


while (count < P) {
int found = 0;

for (int p = 0; p < P; p++) {


if (!finish[p]) {
int canProceed = 1;
for (int j = 0; j < R; j++) {
if (need[p][j] > work[j]) {
canProceed = 0;
break;
}
}

if (canProceed) {
for (int j = 0; j < R; j++) {
work[j] += allocation[p][j];
}
finish[p] = 1;
safeSeq[count++] = p;
found = 1;
break;
}
}
}

if (!found) {
return 0; // No safe sequence found, deadlock detected
}
}

// Safe sequence found

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 59


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

printf("Safe Sequence: ");


for (int i = 0; i < P; i++) {
printf("P%d ", safeSeq[i]);
}
printf("\n");

return 1; // System is in a safe state


}

// Function to request resources (for Deadlock Avoidance)


int requestResources(int pid, int request[]) {
// Check if request is valid
for (int i = 0; i < R; i++) {
if (request[i] > need[pid][i]) {
printf("Error: Process has exceeded its maximum claim.\n");
return 0;
}
if (request[i] > available[i]) {
printf("Error: Not enough resources available.\n");
return 0;
}
}

// Pretend to allocate resources


for (int i = 0; i < R; i++) {
available[i] -= request[i];
allocation[pid][i] += request[i];
need[pid][i] -= request[i];
}

// Check if system is in a safe state


if (isSafe()) {

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 60


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

return 1;
} else {
// Rollback
for (int i = 0; i < R; i++) {
available[i] += request[i];
allocation[pid][i] -= request[i];
need[pid][i] += request[i];
}
printf("Error: Request cannot be granted (would lead to deadlock).\n");
return 0;
}
}

int main() {
// Input Allocation Matrix
printf("Enter the Allocation matrix (5x3):\n");
for (int i = 0; i < P; i++) {
for (int j = 0; j < R; j++) {
scanf("%d", &allocation[i][j]);
}
}

// Input Maximum Matrix


printf("Enter the Max matrix (5x3):\n");
for (int i = 0; i < P; i++) {
for (int j = 0; j < R; j++) {
scanf("%d", &max[i][j]);
}
}

// Input Available Resources


printf("Enter the Available resources (3 values):\n");

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 61


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

for (int i = 0; i < R; i++) {


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

// Calculate the Need Matrix


calculateNeed();

// Check if the system is in a safe state using Banker's Algorithm


printf("\nChecking if the system is in a safe state...\n");
if (isSafe()) {
printf("No Deadlock Detected!\n");
} else {
printf("Deadlock Detected!\n");
}

// Example Resource Request for Deadlock Avoidance


int pid, request[R];
printf("\nEnter the process ID (0 to 4) to request resources: ");
scanf("%d", &pid);
printf("Enter the resource request for process P%d: ", pid);
for (int i = 0; i < R; i++) {
scanf("%d", &request[i]);
}

// Request Resources for Deadlock Avoidance


if (requestResources(pid, request)) {
printf("Resources successfully allocated to process P%d.\n", pid);
} else {
printf("Resources could not be allocated to process P%d.\n", pid);
}

return 0;

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 62


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

}
OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 63


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

4. C PROGRAMS TO SIMULATE FREE SPACE MANAGEMENT


(FIRST FIT,BEST FIT,WORST FIT):
1. FIRST FIT:
#include <stdio.h>

Void firstfit(int blocksize[], int m, int processsize[], int n) {


// array to store the index of the block allocated to a process
int allocation[n];

// initially, no block is assigned to any process


for (int i = 0; i < n; i++) {
allocation[i] = -1;
}

// allocate blocks to processes


for (int i = 0; i < n; i++) {
// find the first block that is large enough for the process
for (int j = 0; j < m; j++) {
if (blocksize[j] >= processsize[i]) {
// allocate the block to the process
allocation[i] = j;
// reduce the size of the free block
blocksize[j] -= processsize[i];
break;
}
}
}

// print the allocation results


printf("process no.\tprocess size\tblock no.\tblock size\n");
for (int i = 0; i < n; i++) {
if (allocation[i] != -1) {

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 64


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

printf("%d\t\t%d\t\t%d\t\t%d\n", i+1, processsize[i], allocation[i]+1,


blocksize[allocation[i]]);
} else {
printf("%d\t\t%d\t\tnot allocated\n", i+1, processsize[i]);
}
}
}

Int main() {
int m, n;

// input number of memory blocks and processes


printf("enter the number of blocks: ");
scanf("%d", &m);

printf("enter the number of processes: ");


scanf("%d", &n);

int blocksize[m], processsize[n];

printf("enter the sizes of the memory blocks:\n");


for (int i = 0; i < m; i++) {
scanf("%d", &blocksize[i]);
}

printf("enter the sizes of the processes:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &processsize[i]);
}

// run the first-fit algorithm


firstfit(blocksize, m, processsize, n);

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 65


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

return 0;
}
Output:

2. BEST FIT:
#include <stdio.h>
Int main()
{
Int a[20], b[20], c[20], b1, c1;
Int i, j, temp;
Static int barr[20], carr[20];
Printf("\n\t\t\tmemory management"" scheme - best fit");
Printf("\nenter the number of ""blocks:");
Scanf("%d", &b1);
Printf("enter the number of"" processes:");
Scanf("%d", &c1);
Int lowest = 9999;
Printf("\nenter the size of the"" blocks:\n");
For (i = 1; i <= b1; i++)
{
Printf("block no.%d:", i);
Scanf("%d", &b[i]);
}
Printf("\nenter the size of"" the processes :\n");

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 66


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

For (i = 1; i <= c1; i++)


{
Printf("process no.%d:", i);
Scanf("%d", &c[i]);
}
For (i = 1; i <= c1; i++)
{
For (j = 1; j <= b1; j++)
{
If (barr[j] != 1)
{
Temp = b[j] - c[i];
If (temp >= 0)
If (lowest > temp)
{
Carr[i] = j;
Lowest = temp;
}
}
}
A[i] = lowest;
Barr[carr[i]] = 1;
Lowest = 10000;
}
Printf("\nprocess_no\tprocess""_size\tblock_no\t""block_size\tfragment");
For (i = 1; i <= c1 && carr[i] != 0; i++)
{
Printf("\n%d\t\t%d\t\t%d\t\t""%d\t\t%d", i, c[i], carr[i], b[carr[i]], a[i]);
}
Printf("\n");
}
Output:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 67


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

3. WORST FIT:

#include <stdio.h>
#define max 10
// function to find the largest free block
Int worstfit(int blocksize[], int m, int processsize[], int n) {
// stores the result (the allocation status of processes)
Int allocation[n];
// initialize all processes as not allocated
For (int i = 0; i < n; i++) {
Allocation[i] = -1;
}

// loop through all processes


For (int i = 0; i < n; i++) {
// find the largest block that is sufficient for the current process
Int maxindex = -1;
For (int j = 0; j < m; j++) {
If (blocksize[j] >= processsize[i]) {

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 68


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

If (maxindex == -1 || blocksize[j] > blocksize[maxindex]) {


Maxindex = j;
}
}
}

// if we found a valid block, allocate the process to it


If (maxindex != -1) {
Allocation[i] = maxindex;
Blocksize[maxindex] -= processsize[i]; // update the block size
}
}

// output the allocation


Printf("\nprocess no.\tprocess size\tblock no.\n");
For (int i = 0; i < n; i++) {
If (allocation[i] != -1) {
Printf("%d\t\t%d\t\t%d\n", i + 1, processsize[i], allocation[i] + 1);
} else {
Printf("%d\t\t%d\t\tnot allocated\n", i + 1, processsize[i]);
}
}

Return 0;
}
Int main() {
// size of memory blocks
Int blocksize[max] = {100, 500, 200, 300, 600};
// size of processes
Int processsize[max] = {212, 417, 112, 426};
Int m = sizeof(blocksize) / sizeof(blocksize[0]);
Int n = sizeof(processsize) / sizeof(processsize[0]);

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 69


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

// call the function to perform worst-fit memory allocation


Worstfit(blocksize, m, processsize, n);
Return 0;
}
Output:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 70


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

5. C PROGRAMS TO STUDY DISK SCHEDULING ALGORITHMS (I.E


SCAN, SSTF,LOOK,ETC):
#include <stdio.h>
#include <stdlib.h>
#define MAX_CYLINDERS 200
// Function to sort the requests in ascending order
void sort_requests(int arr[], int n) {
int temp;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

// Function to implement SCAN Disk Scheduling Algorithm


void scan(int requests[], int n, int start, int direction) {
int total_distance = 0;
int left[MAX_CYLINDERS], right[MAX_CYLINDERS];
int left_index = 0, right_index = 0;

// Divide requests into two lists: left and right of the start position
for (int i = 0; i < n; i++) {
if (requests[i] < start) {
left[left_index++] = requests[i];
} else {
right[right_index++] = requests[i];
}

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 71


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

// Sort both left and right arrays


sort_requests(left, left_index);
sort_requests(right, right_index);

// Calculate total distance by moving in one direction


if (direction == 1) { // Moving right first
total_distance += (right[right_index - 1] - start);
total_distance += (right[right_index - 1] - left[0]);
} else { // Moving left first
total_distance += (start - left[left_index - 1]);
total_distance += (right[right_index - 1] - left[0]);
}

printf("Total Seek Distance for SCAN: %d\n", total_distance);


}

// Function to implement SSTF (Shortest Seek Time First) Disk Scheduling Algorithm
void sstf(int requests[], int n, int start) {
int total_distance = 0;
int visited[MAX_CYLINDERS] = {0};
int count = 0;
int current_position = start;

// Continue servicing requests until all are visited


while (count < n) {
int min_distance = MAX_CYLINDERS;
int min_index = -1;

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


if (!visited[i]) {

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 72


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

int distance = abs(current_position - requests[i]);


if (distance < min_distance) {
min_distance = distance;
min_index = i;
}
}
}

// Visit the closest request


visited[min_index] = 1;
total_distance += min_distance;
current_position = requests[min_index];
count++;
}

printf("Total Seek Distance for SSTF: %d\n", total_distance);


}

// Function to implement LOOK Disk Scheduling Algorithm


void look(int requests[], int n, int start, int direction) {
int total_distance = 0;
int left[MAX_CYLINDERS], right[MAX_CYLINDERS];
int left_index = 0, right_index = 0;

// Divide requests into two lists: left and right of the start position
for (int i = 0; i < n; i++) {
if (requests[i] < start) {
left[left_index++] = requests[i];
} else {
right[right_index++] = requests[i];
}
}

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 73


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

// Sort both left and right arrays


sort_requests(left, left_index);
sort_requests(right, right_index);
// Calculate total distance by moving in one direction (no need to go to the extremes)
if (direction == 1) { // Moving right first
total_distance += (right[right_index - 1] - start);
total_distance += (right[right_index - 1] - left[0]);
} else { // Moving left first
total_distance += (start - left[left_index - 1]);
total_distance += (right[right_index - 1] - left[0]);
}
printf("Total Seek Distance for LOOK: %d\n", total_distance);
}
// Main function to run the disk scheduling algorithms
int main() {
int n, start, direction;
printf("Enter the number of disk requests: ");
scanf("%d", &n);

int requests[n];
printf("Enter the disk requests: ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}
printf("Enter the starting position of the disk head: ");
scanf("%d", &start);
printf("Enter the direction (1 for right, 0 for left): ");
scanf("%d", &direction);
// Call SCAN Disk Scheduling
scan(requests, n, start, direction);
// Call SSTF Disk Scheduling
sstf(requests, n, start);

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 74


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

// Call LOOK Disk Scheduling


look(requests, n, start, direction);
return 0;
}
OUTPUT:

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 75


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

VIVA QUESTIONS

1. What is the function of the ls command in Unix?

1. The ls command is used to list the files and directories in the current working directory.

2. How do you create a new file in the Vi editor?

2. To create a new file in the Vi editor, type vi filename, and the editor will open a new file if
it doesn't already exist.

3.What does the command chmod do in Unix?

3. The chmod command is used to change the permissions of a file or directory in Unix.

4. What is the purpose of a shell script?

4. A shell script is used to automate tasks by executing a series of commands in a sequence.

5. How do you run a shell script in Unix?

5. To run a shell script, use the command ./scriptname.sh after giving it executable permissions
using chmod +x scriptname.sh.

6. What is the purpose of the if statement in shell scripting?

6. The if statement allows the shell script to make decisions based on conditional expressions.

7 .How would you check if a file exists in a shell script?

7. You can check if a file exists using the condition if [ -e filename ]; then in a shell script.

8. What is the purpose of the for loop in shell scripting?

8. The for loop is used to repeat a set of commands for a specific number of times or over a list
of items.

9. How can you pass command-line arguments to a C program?

9. Command-line arguments can be passed by using argc (argument count) and argv[]
(argument vector) in the main function: int main(int argc, char *argv[]).

10. What is the fork() system call used for?

10. The fork() system call is used to create a new process by duplicating the calling process.

11. What is the purpose of the make utility in C programming?

11. The make utility automates the process of compiling and building projects by reading
instructions from a Make file.
SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 76
DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

12. What is the difference between a parent process and a child process in C?

12. The parent process is the original process that calls fork(), and the child process is the new
process created by fork().

13. What function is used to terminate a process in C?

13. The exit() function is used to terminate a process in C.

14. What is process chaining?

14. Process chaining refers to the sequence of creating multiple processes where one process
may create another, and so on.

15. How do you spawn a process in C?

15. A process can be spawned using fork() or exec() system calls in C.

16. What is the use of the errno variable in C?

16. The errno variable stores error codes set by system calls and library functions to indicate
the type of error that occurred.

17. What does the perror() function do in C?

17. The perror() function prints a descriptive error message to the standard error stream, based
on the value of errno.

18. What is the pipe() system call used for?

18. The pipe() system call creates a unidirectional communication channel between two
processes for inter-process communication.

19. How do you use pipes for communication between processes in C?

19. A pipe is created using pipe() and the file descriptors returned are used to read and write
between processes.

20. What is the First-Come, First-Served (FCFS) scheduling algorithm?

20. FCFS is a non-preemptive scheduling algorithm where the process that arrives first is
executed first.

21. How does the Shortest Job First (SJF) scheduling algorithm work?

21. SJF schedules the process with the shortest burst time first, aiming to minimize waiting
time.

22. What is the Round Robin scheduling algorithm?

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 77


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

22. Round Robin is a preemptive scheduling algorithm that assigns each process a fixed time
slice (quantum) in a circular order.

23. What is the FIFO page replacement algorithm?

23. FIFO (First In, First Out) replaces the oldest page in memory when a page fault occurs.

24. How does the Least Recently Used (LRU) page replacement algorithm work?

24. LRU replaces the page that has not been used for the longest time when a page fault occurs.

25. What is the Optimal page replacement algorithm?

25. The Optimal page replacement algorithm replaces the page that will not be used for the
longest time in the future.

26. What is deadlock in operating systems?

26. Deadlock occurs when a set of processes is blocked because each process is holding a
resource and waiting for another resource held by another process.

27. What is deadlock detection?

27. Deadlock detection involves checking if a set of processes is in a deadlock state by


examining resource allocation and wait-for graphs.

28. What is the "First Fit" memory allocation algorithm?

28. The First Fit algorithm allocates the first available memory block that is large enough to
accommodate the requested process.

29. What is the "Best Fit" memory allocation algorithm?

29. The Best Fit algorithm allocates the smallest available memory block that can
accommodate the process, aiming to minimize wasted space.

30. What is the "Worst Fit" memory allocation algorithm?

30. The Worst Fit algorithm allocates the largest available memory block to a process, aiming
to leave large contiguous free spaces.

31. What is the SCAN disk scheduling algorithm?

31. SCAN moves the disk arm from one end to the other, servicing requests, and then reverses
direction when it reaches the end.

32. What is the SSTF (Shortest Seek Time First) disk scheduling algorithm?

32. SSTF selects the disk request that is closest to the current disk arm position.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 78


DEPARTEMENT OF COMPUTER SCIENCE AND ENGINEERING

33. What is the LOOK disk scheduling algorithm?

33. LOOK is similar to SCAN, but instead of going to the end of the disk, it stops when there
are no more requests in the current direction.

SANKETIKA VIDYA PARISHAD ENGINEERING COLLEGE 79

You might also like