KEMBAR78
22cdl44 Os Lab Manual - Os - Final | PDF | Computer File | Engineering
0% found this document useful (0 votes)
10 views41 pages

22cdl44 Os Lab Manual - Os - Final

The document outlines the Operating Systems Lab course for the Department of Computer Science & Engineering at New Horizon College of Engineering, detailing its vision, mission, quality policy, and program outcomes. It specifies course outcomes, a list of experiments, assessment patterns, and suggested learning resources. The lab focuses on practical skills in Linux commands, process management, CPU scheduling, deadlock detection, and file organization techniques.

Uploaded by

spamyuvraj555
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)
10 views41 pages

22cdl44 Os Lab Manual - Os - Final

The document outlines the Operating Systems Lab course for the Department of Computer Science & Engineering at New Horizon College of Engineering, detailing its vision, mission, quality policy, and program outcomes. It specifies course outcomes, a list of experiments, assessment patterns, and suggested learning resources. The lab focuses on practical skills in Linux commands, process management, CPU scheduling, deadlock detection, and file organization techniques.

Uploaded by

spamyuvraj555
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/ 41

Department of Computer Science & Engineering (Data Science)

Operating Systems Lab

Course Code: 22CDL44

Semester: IV AY: 2023-24

Prepared By Approved By Authorized By

Dr. Suganya. R
Dr. Suganya. R
& Dr.B.Swathi

T.Sasikala
NEW HORIZON COLLEGE OF ENGINEERING

VISION

To emerge as an institute of eminence in the fields of engineering, technology


and management in serving the industry and the nation by empowering students
with a high degree of technical, managerial and practical competence.

MISSION

To strengthen the theoretical, practical and ethical dimensions of the learning


process by fostering a culture of research and innovation among faculty members
and students.

To encourage long-term interaction between the academia and industry through


their involvement in the design of curriculum and its hands-on implementation.

To strengthen and mould students in professional, ethical, social and


environmental dimensions by encouraging participation in co-curricular and
extracurricular activities

QUALITY POLICY

To provide educational services of the highest quality both curricular and co-
curricular to enable students integrate skills and serve the industry and society
equally well at global level.

VALUES
• Academic Freedom
• Integrity Inclusiveness
• Innovation
• Professionalism
• Social Responsibility
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING (DATA SCIENCE)

PROGRAM OUTCOMES (Pos)

PO1 Engineering Knowledge: Apply knowledge of mathematics, science, engineering


fundamentals and an engineering specialization to the solution of complex Computer Science
and Data Science engineering problems.

PO2 Problem Analysis: Identify, formulate, review research literature and analyze complex
Computer Science and Data Science engineering problems reaching substantiated conclusions
using first principles of mathematics, natural sciences and engineering sciences.

PO3 Design / Development of Solutions: Design solutions for complex Computer Science
and Data Science engineering problems and design system components or processes that meet
specified needs with appropriate consideration for public health and safety, cultural, societal
and environmental considerations.

PO4 Conduct Investigations of Complex Problems:


Use research-based knowledge and research methods including design of experiments, analysis
and interpretation of data and synthesis of the information to provide valid conclusions.

PO5 Modern tool usage: Create, select and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modelling to complex Computer
Science and Data Science engineering activities with an understanding of the limitations.

PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice in Computer Science and Data Science
Engineering.

PO7 Environment and sustainability: Understand the impact of the professional engineering
solutions in Computer Science and Data Science engineering in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable development.

PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.

PO9 Individual and Team Work: Function effectively as an individual and as a member or
leader to diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex Computer Science and Data
Science engineering activities with the engineering community and with society at large, such
as, being able to comprehend and write effective report and design documentation, make
effective presentations, and give and receive clear instructions.

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

PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO1
Apply data analysis techniques, algorithmic expertise, and advanced modelling to
effectively solve complex problems across various domains demonstrating their
capacity to derive insights and propose innovative solutions in the realm of data-driven
technologies.

PSO2
Collaborate proficiently with experts from diverse fields and actively engage in
continuous professional growth in the domain of Computer Science and Engineering,
specializing in the field of Data Science.
OPERATING SYSTEMS LAB
Course Code 22CDL44 CIE Marks 50
L:T:P:S 0:0:1:0 SEE Marks 50
Hrs / Week 2 Total Marks 100
Credits 01 Exam Hours 03
Course outcomes:
At the end of the course, the student will be able to:
22CDL44.1 Demonstrate the basic knowledge of Linux commands and file handling utilities by using Linux
shell environment.
22CDL44.2 Examine the various process scheduling algorithms
22CDL44.3 Implement various operations on deadlock
22CDL44.4 Implement various File Organization, File Allocation Strategies and Disk Scheduling Algorithms.
Mapping of Course Outcomes to Program Outcomes and Program Specific Outcomes:
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
22CDL44.1 3 2 2 2 3 - - - - - - 1 3 3
22CDL44.2 3 2 2 2 3 - - - - - - 1 3 3
22CDL44.3 3 2 2 2 3 - - - - - - 1 3 3
22CDL44.4 3 2 2 2 3 - - - - - - 1 3 3

Pgm. No. List of Programs Hours Cos


Prerequisite Programs

• To understand the basics of Unix command and shell programming.


• To implement various CPU scheduling algorithms.
• To implement Deadlock Avoidance and Deadlock Detection Algorithms 2 NA
• To implement Page Replacement Algorithms
• To implement various memory allocation methods.
• To be familiar with File Organization and File Allocation Strategies.
PART-A
1 Introduction- Linux Architecture- Shell, Kernel, System calls.
Linux installation- Steps for installing Linux Operating System
Internal & External commands in Linux.
• Internal commands- echo, type, etc.
• External commands- ls, cp, mv, rm, cat, etc 2 22CDL44.1
• Other commands – tput clear, who, cal, date, bc, man, passwd,
uname( with different options).
• Expressions & search patterns .(dot operator), *, A, +, ?, grep,
egrep, fgrep
2 Working with files & directories.
• Know the categories of files.
• Directory related Commands – pwd, mkdir, rmdir, cd, ls
• Manipulating Absolute paths and Relative paths using cd
command.
• File related Commands – cat, cp, mv, rm, comm, cmp, diff, tar,
2 22CDL44.1
umask, wc
Basic File attributes.
• Listing seven attributes of a file : ls and its options
• File Permissions: Absolute and Relative permissions
• Manipulating File permissions using chmod command
• Manipulating File Ownership using chown command
• Manipulating Hardlink and Softlink using ln command
3 Process Management commands.
• Process creation, status, Identifying process, ps -f &its options,
• Running process in background, Job control, and Proces2termination. 2 22CDL44.1
Changing process priority, scheduling process (Usage of sleep and wait
commands)
4 Design, Develop and Implementation of CPU scheduling by using
a. FCFS 2 22CDL44.2
b. Priority
5 Design, Develop and Implementation of CPU scheduling by
a. SJF 2 22CDL44.2
b. Round Robin
6 Design, Develop and Implement Threading and synchronized applications 2 22CDL44.3
PART-B
7 Design, Develop and Implement an Algorithm for Dead Lock Detection. 2 22CDL44.3
8 Design, Develop and Implement an Algorithm for Deadlock using Banker’s
2 22CDL44.3
Algorithm.
9 Design, Develop and Implement a Program by using page replacement
2 22CDL44.3
algorithms for virtual memory management
10 Design, Develop and Implement the various File Organization Techniques 2 22CDL44.4
11 Design, Develop and Implement the following File Allocation Strategies
a. Sequential
2 22CDL44.4
b. Indexed
c. Linked
12 Design, Develop and Implement various disk scheduling algorithms 2 22CDL44.4
PART-C
Beyond Syllabus Virtual Lab Content
(To be done during Lab but not to be included for CIE or SEE)
• Dead lock, Scheduling https://naim30.github.io/OS-virtual-lab/
CIE Assessment Pattern (50 Marks – Lab)
CIE Assessment Pattern (50 Marks – Lab)

RBT Levels Test Weekly Assesment


20 30
L1 Remember - -
L2 Understand - -
L3 Appy 10 15
L4 Analyze 5 10
L5 Evaluate 5 5
L6 Create - -

SEE Assessment Pattern (50 Marks – Lab)

RBT Levels Exam Marks


Distribution(50)
L1 Remember -
L2 Understand --
L3 Appy 15
L4 Analyze 20
L5 Evaluate 15
L6 Create --
Suggested Learning Resources:
Reference Books
1. Abraham Silberschatz, Peter Baer Galvin, Greg Gagne, Operating System Principles 7th edition,
Wiley-India, 2006
2. Silber schatz, Galvin, Greg, “Operating System Concepts”, Wiley and Sons, 10th Edition, 2018.
3. William Stallings, “Operating Systems – Internals and Design Principles”, 9th Edition, Prentice
Hall, 2018.
4. Andrew S Tanenbaum, Albert S Woodhull, “Operating systems design and implementation”,
3rd edition.
5. UNIX-Concepts Applications, SUMITABHADAS, McGraw Hill, TATA McGraw HillEdition,
4th edition, 26th reprint 2019.
6. D M Dhamdhere, “Operating Systems: A Concept-Based Approach”, 3rd Edition,
Tata McGraw Hill Education,2017
S.No List of Experiments Page
No
1 Introduction- Linux Architecture- Shell, Kernel, System calls. Linux
installation- Steps for installing Linux Operating System Internal & External
commands in Linux. 1
• Internal commands- echo, type, etc.
• External commands- ls, cp, mv, rm, cat, etc
• Other commands – tput clear, who, cal, date, bc, man, passwd, uname(
with different options).
• Expressions & search patterns .(dot operator), *, A, +, ?, grep,
• egrep, fgrep
2 Working with files & directories. 4
• Know the categories of files.
• Directory related Commands – pwd, mkdir, rmdir, cd, ls
• Manipulating Absolute paths and Relative paths using cd
command.
• File related Commands – cat, cp, mv, rm, comm, cmp, diff, tar, umask,
wc
Basic File attributes.
• Listing seven attributes of a file : ls and its options
• File Permissions: Absolute and Relative permissions
• Manipulating File permissions using chmod command
Manipulating File Ownership using chown command
3 Process Management commands. 8
• Process creation, status, Identifying process, ps -f &its options,
• Running process in background, Job control, and Proces2termination.
Changing process priority, scheduling process (Usage of sleep and wait commands)
4 Design, Develop and Implementation of CPU scheduling by using 10
FCFS
Priority

5 Design, Develop and Implementation of CPU scheduling by 14


SJF
Round Robin

6 Design, Develop and Implement Threading and synchronized applications 17

7 Design, Develop and Implement an Algorithm for Dead Lock Detection. 18


8 Design, Develop and Implement an Algorithm for Deadlock using Banker’s 22
Algorithm.

9 Design, Develop and Implement a Program by using page replacement 24


algorithms for virtual memory management

10 Design, Develop and Implement the various File Organization Techniques 26

11 Design, Develop and Implement the following File Allocation Strategies 29


d. Sequential
e. Indexed
Linked
12 Design, Develop and Implement various disk scheduling algorithms 31
PART-A
1. Introduction- Linux Architecture- Shell, Kernel, System calls. Linux installation- Steps
for installing Linux Operating System Internal & External commands in Linux.
● Internal commands- echo, type, etc.
● External commands- ls, cp, mv, rm, cat, etc
● Other commands – tput clear, who, cal, date, bc, man, passwd, uname( with different
options).
● Expressions & search patterns.(dot operator), *, A, +, ?, grep, egrep, fgrep

1. echo command: echo command in linux is used to display line of text/string that
are passed as an argument . This is a built in command that is mostly used in shell
scripts and batch files to output status text to the screen or a file.
echo [string]
2. ls( listing files) is used to show list of files on your UNIX or Linux system.

3. ls-l is used To show long listing information about the file/directory.


4. cp: copy the contents of one file to another
5. mv stands for move. mv is used to move one or more files or directories from one
place to another in a file system like UNIX. It has two distinct functions:
(i) It renames a file or folder.
(ii) It moves a group of files to a different directory. rm: remove a particular file.
6. cat(concatenate) command is very frequently used in Linux. It reads data from the
file and gives their content as output. It helps us to create, view, concatenate files.
7. clear is a standard Unix computer operating system command that is used to clear
the terminal screen
8. who command is used to find out the following information :
1. Time of last system boot
2. Current run level of the system
3. List of logged in users and more.
9. cal: displays the calendar of the current month.
10. date: displays current date.
11. bc Command
The bc command is an interactive process that provides arbitrary-precision
arithmetic. ...
The bc command is a preprocessor for the dc command. ...
The bc command allows you to specify an input and output base for operations in
decimal, octal, or hexadecimal.
12.man command in Linux is used to display the user manual of any command that we
can run on the terminal.
13. passwd command changes passwords for user accounts. A normal user may only
change the password for their own account, while the superuser may change the
password for any account. passwd also changes the account or associated password
validity period.
14. The command ‘uname‘ displays the information about the system.
-a option: It prints all the system information in the following order: Kernel
name, network node hostname, kernel release date, kernel version, machine
hardware name, hardware platform, operating system
-s option: It prints the kernel name.
15. grep filter searches a file for a particular pattern of characters, and displays all
lines that contain that pattern. The pattern that is searched in the file is referred to as
the regular expression (grep stands for global search for regular expression and print
out).
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.

-A n : Prints searched line and nlines after the result.


-B n : Prints searched line and n line before the result.
-C n : Prints searched line and n lines after before the result.

16.egrep is a pattern searching command which belongs to the family of grep functions. It
works the same way as grep -E does. It treats the pattern as an extended regular expression
and prints out the lines that match the pattern. If there are several files with the matching
pattern, it also displays the file names for each line.
Syntax:
egrep [ options ] 'PATTERN' files
17.fgrep filter is used to search for the fixed-character strings in a file. There can be multiple
files also to be searched. This command is useful when you need to search for strings which
contain lots of regular expression metacharacters, such as “^”, “$”, etc.

Syntax:
fgrep [options] [ -e pattern_list] [pattern] [file]
Options with Description:

• -c : It is used to print only a count of the lines which contain the pattern.
• -h : Used to display the matched lines.
• -i : During comparisons, it will ignore upper/lower case distinction.
• -l : Used to print the names of files with matching lines once, separated by new-
lines. It will not repeat the names of files when the pattern is found more than
once.
• -n : It is used precede each line by its line number in the file (first line is 1).
• -s : It will only display the error messages.
• -v : Print all lines except those contain the pattern.
• -x : Print only lines matched entirely.
• -e pattern_list : Search for a string in pattern-list (useful when the string begins
with a “-“).
• -f pattern-file : Take the list of patterns from pattern-file.
• pattern : Specify a pattern to be used during the search for input.
• file : A path name of a file to be searched for the patterns. If no file operands are
specified, the standard input will be used.
2. Working with files & directories.
● Know the categories of files.
● Directory related Commands – pwd, mkdir, rmdir, cd, ls
● Manipulating Absolute paths and Relative paths using cd command.
● File related Commands – cat, cp, mv, rm, comm, cmp, diff, tar, umask, wc
● Listing seven attributes of a file : ls and its options
● File Permissions: Absolute and Relative permissions
● Manipulating File permissions using chmod command
● Manipulating File Ownership using chown command
● Manipulating Hardlink and Softlink using ln command
In Linux, everything is considered as a file. In UNIX, seven standard file types are regular,
directory, symbolic link, FIFO special, block special, character special, and socket. In
Linux/UNIX, we have to deal with different file types to manage them efficiently.
In Linux/UNIX, Files are mainly categorized into 3 parts:
1. Regular Files ,Directory Files
2. Special Files
The easiest way to find out file type in any operating system is by looking at its extension
such as .txt, .sh, .py, etc. If the file doesn’t have an extension then in Linux we can
use file utility. In this article, we will demonstrate file command examples to determine a
file type in Linux.

To find out file types we can use the file command.


Syntax: file [OPTION…] [FILE…]
file -v
We can test a file type by typing the following command:
file file.txt
1. pwd stands for Print Working Directory: It prints the path of the working directory,
starting from the root. pwd is shell built-in command(pwd) or an actual
binary(/bin/pwd).

2. mkdir command in Linux allows the user to create directories (also referred to as
folders in some operating systems ). This command can create multiple directories
at once as well as set the permissions for the directories.

3. rmdir command is used remove empty directories from the filesystem in Linux.
The rmdir command removes each and every directory specified in the command
line only if these directories are empty.

4. cd command in linux known as change directory command. It is used to change


current working directory.
5. ls( listing files) is used to show list of files on your UNIX or Linux system.

6.cat(concatenate) command is very frequently used in Linux. It reads data from the
file and gives their content as output. It helps us to create, view, concatenate files.
7.cp: copy the contents of one file to another
8.rm: remove a particular file.
9.comm
Syntax :
$comm [OPTION]... FILE1 FILE2
• As using comm, we are trying to compare two files therefore the syntax of comm
command needs two filenames as arguments.
cmp command in Linux/UNIX is used to compare the two files byte by byte and helps
you to find out whether the two files are identical or not.
Syntax:
cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]

diff stands for difference. This command is used to display the differences in the files
by comparing the files line by line. Unlike its fellow members, cmp and comm, it tells us
which lines in one file have is to be changed to make the two files identical.

The important thing to remember is that diff uses certain special


symbols and instructions that are required to make two files identical. It tells you the
instructions on how to change the first file to make it match the second file.
diff [options] File1 File2

tar stands for tape archive, is used to create Archive and extract the Archive files. tar
command in Linux is one of the important command which provides archiving functionality
in Linux. We can use Linux tar command to create compressed or uncompressed Archive
files and also maintain and modify them.
The umask command in Linux is used to set default permissions for files or directories the
user creates.
• The umask command specifies the permissions that the user does not want to be
given out to the newly created file or directory.
• umask works by doing a Bitwise AND with the bitwise complement (where the
bits are inverted, i.e. 1 becomes 0 and 0 becomes 1) of the umask.
• The bits which are set in the umask value, refer to the permissions, which are not
assigned by default, as these values are subtracted from the maximum permission
for files/directories.
$umask
wc stands for word count. As the name implies, it is mainly used for counting purpose.
• It is used to find out number of lines, word count, byte and characters count in
the files specified in the file arguments.
• By default it displays four-columnar output.
• First column shows number of lines present in a file specified, second column
shows number of words present in the file, third column shows number of
characters present in file and fourth column itself is the file name which are given
as argument.

$ wc filename

Syntax:- ls -l

• The file type.


• The file permissions.
• Number of hard links to the file.
• File owner.File group. File size.
• Date and Time.
• File name.

$ ls -l /etc/hosts
-rw-r--r-- 1 root root 337 Oct 4 11:31 /etc/hosts

chmod command is used to change the access mode of a file.


The name is an abbreviation of change mode.
chmod [reference][operator][mode] file...
The references are used to distinguish the users to whom the permissions apply i.e. they are
list of letters that specifies whom to give permissions. The references are represented by one
or more of the following letters:

Reference Class Description


u owner file's owner

g group users who are members of


the file's group

o others users who are neither the


file's owner nor members of
the file's group

a all All three of the above, same as ugo


chown command is used to change the file Owner or group. Whenever you want to change
ownership you can use chown command.
chown [OPTION]… [OWNER][:[GROUP]] FILE…
chown [OPTION]… –reference=RFILE FILE…
Example: To change owner of the file:
chown owner_name file_name

Hard Links

• Each hard linked file is assigned the same Inode value as the original, therefore
they reference the same physical file location. Hard links more flexible and remain
linked even if the original or linked files are moved throughout the file system,
although hard links are unable to cross different file systems.
• ls -l command shows all the links with the link column shows number of links.
• Links have actual file contents

Syntax:-$ ln [original filename] [link name]


3. Process Management commands.
● Process creation, status, Identifying process, ps -f &its options,
● Running process in background, Job control, and Process termination.
● Changing process priority, scheduling process (Usage of sleep and wait commands)
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid, mypid, myppid;
pid = getpid();
printf("Before fork: Process id is %d\n", pid);
pid = fork();

if (pid < 0)
{
perror("fork() failure\n");
return 1;
}
// Child process
if (pid == 0)
{
printf("This is child process\n");
mypid = getpid();
myppid = getppid();
printf("Process id is %d and PPID is %d\n", mypid, myppid);
}
else
{ // Parent process

sleep(2);
printf("This is parent process\n");
mypid = getpid();
myppid = getppid();
printf("Process id is %d and PPID is %d\n", mypid, myppid);
printf("Newly created process id or child pid is %d\n", pid);
}
return 0;
}
Before fork: Process id is 166629
This is child process
Process id is 166630 and PPID is 166629
Before fork: Process id is 166629
This is parent process
Process id is 166629 and PPID is 166628
Newly created process id or child pid is 166630
4. Design, Develop and Implementation of CPU scheduling by using
a. FCFS
b. Priority
DESCRIPTION

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.
Program:
FCFS Scheduling:
#include<stdio.h>
#include<conio.h>
main()
{
int bt[20], wt[20], tat[20], i, n;
float wtavg, tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{

printf("\nEnter Burst Time for Process %d -- ", i);


scanf("%d", &bt[i]);
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
}

Output:
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.
PRIORITY CPU SCHEDULING
#include<stdio.h>
#include<conio.h>
struct process
{
int pid;
int bt;

int wt;
int tt;
int prior;
}
p[10],temp;
int main()
{
int i,j,n,totwt,tottt,arg1,arg2;
clrscr();
printf("enter the number of process");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("enter the burst time");
scanf("%d",&p[i].bt);
printf("\n enter the priority");
scanf("%d",&p[i].prior);
}
for(i=1;i<n;i++)
{
for(j=i+1;j<=n;j++)
{
if(p[i].prior>p[j].prior)
{
temp.pid=p[i].pid;
p[i].pid=p[j].pid;
p[j].pid=temp.pid;
temp.bt=p[i].bt;
p[i].bt=p[j].bt;
p[j].bt=temp.bt;
temp.prior=p[i].prior;
p[i].prior=p[j].prior;
p[j].prior=temp.prior;
}}
}
p[i].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n)
{
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
i++;
}
i=1;
totwt=tottt=0;
printf("\n process to \t bt \t wt \t tt");
while(i<=n)

{
printf("\n%d\t %d\t %d\t %d\t",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
arg1=totwt/n;
arg2=tottt/n;
printf("\n arg1=%d \t arg2=%d\t",arg1,arg2);
getch();
return 0;
}
Output:
5. Design, Develop and Implementation of CPU scheduling by
a. SJF
b. Round Robin

DESCRIPTION
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.
SJF CPU SCHEDULING:
#include<stdio.h>
#include<conio.h>
struct process
{
int pid;

int bt;
int wt;
int tt;
}p[10],temp;
int main()
{
int i,j,n,totwt,tottt;
float avg1,avg2;
clrscr();
printf("\nEnter the number of process:\t");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("\nEnter the burst time:\t");
scanf("%d",&p[i].bt);
}
for(i=1;i<n;i++){
for(j=i+1;j<=n;j++)
{
if(p[i].bt>p[j].bt)
{
temp.pid=p[i].pid;
p[i].pid=p[j].pid;
p[j].pid=temp.pid;
temp.bt=p[i].bt;p[i].bt=p[j].bt;
p[j].bt=temp.bt;
}}}
p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n){
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
i++;
}
i=1;
totwt=tottt=0;
printf("\nProcess id \tbt \twt \ttt");
while(i<=n){
printf("\n\t%d \t%d \t%d t%d\n",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
} avg1=totwt/n;
avg2=tottt/n;
printf("\nAVG1=%f\t AVG2=%f",avg1,avg2);
getch();
return 0; }

Output:

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.

Program:

Round Robin Scheduling:


#include 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<=t)
{
tat[i]=temp+bu[i
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{ wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}

Output:
6. Design, Develop and Implement Threading and synchronized applications

Program:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

pthread_t tid[2];
int counter;

void* trythis(void* arg)


{
unsigned long i = 0;
counter += 1;
printf("\n Job %d has started\n", counter);

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


;
printf("\n Job %d has finished\n", counter);

return NULL;
}
int main(void)
{
int i = 0;
int error;

while (i < 2) {
error = pthread_create(&(tid[i]), NULL, &trythis, NULL);

if (error != 0)
printf("\nThread can't be created : [%s]", strerror(error));
i++;
}

pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);

return 0;
}
Output :
Job 1 has started
Job 2 has started
Job 2 has finished
Job 2 has finished
PART -B
7. Design, Develop and Implement an Algorithm for Dead Lock Detection
#include <stdio.h>
#define MAX_PROCESSES 20
#define MAX_RESOURCES 10

static int mark[MAX_PROCESSES];


int i, j, np, nr;

int main()
{
int alloc[MAX_PROCESSES][MAX_RESOURCES],
request[MAX_PROCESSES][MAX_RESOURCES];
int avail[MAX_RESOURCES], r[MAX_RESOURCES], w[MAX_RESOURCES];
printf("\nEnter the number of processes: ");
scanf("%d", &np);
printf("\nEnter the number of resources: ");
scanf("%d", &nr);

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


printf("\nTotal amount of the resource R%d: ", i + 1);
scanf("%d", &r[i]);
}

printf("\nEnter the request matrix:\n");


for(i = 0; i < np; i++) {
for(j = 0; j < nr; j++) {
scanf("%d", &request[i][j]);
}
}

printf("\nEnter the allocation matrix:\n");


for(i = 0; i < np; i++) {
for(j = 0; j < nr; j++) {
scanf("%d", &alloc[i][j]);
}
}

/* Calculate Available Resources */


for(j = 0; j < nr; j++) {
avail[j] = r[j];
for(i = 0; i < np; i++) {
avail[j] -= alloc[i][j];
}
}
// Marking processes with zero allocation
for(i = 0; i < np; i++) {
int count = 0;

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


if(alloc[i][j] == 0)
count++;
else
break;
}
if(count == nr)
mark[i] = 1;
else
mark[i] = 0;
}

// Initialize W with avail


for(j = 0; j < nr; j++)
w[j] = avail[j];

// Mark processes with request less than or equal to W


for(i = 0; i < np; i++) {
int canbeprocessed = 0;
if(mark[i] != 1) {
for(j = 0; j < nr; j++) {
if(request[i][j] <= w[j])
canbeprocessed = 1;
else {
canbeprocessed = 0;
break;
} }
if(canbeprocessed) {
mark[i] = 1;

for(j = 0; j < nr; j++)


w[j] += alloc[i][j];
}
}
}

// Checking for unmarked processes


int deadlock = 0;
for(i = 0; i < np; i++)
if(mark[i] != 1)
deadlock = 1;

if(deadlock)
printf("\nDeadlock detected\n");
else
printf("\nNo Deadlock possible\n");

return 0;
}

Example Input:

Let's assume we have 3 processes and 3 resources:

1. Number of processes: 3
2. Number of resources: 3

Total resources for each type:

• Resource R1: 10
• Resource R2: 5
• Resource R3: 7

Request matrix:

322
010
211
Allocation matrix:
100
211
314

No Deadlock possible
8. Deadlock Avoidance- Bankers Algorithm
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here

int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4

int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix


{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4

int avail[3] = { 3, 3, 2 }; // Available Resources

int f[n], ans[n], ind = 0;


for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;

for (k = 0; k < 5; k++) {


for (i = 0; i < n; i++) {
if (f[i] == 0) {

int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
} }

if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
} }
} }

int flag = 1;

for(int i=0;i<n;i++)
{
if(f[i]==0)
{
flag=0;
printf("The following system is not safe");
break;
}
}

if(flag==1)
{
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
}

return (0);

}
student@localhost ~]$ cc bank.c -std=c99
[student@localhost ~]$ ./a.out
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2[student@localhost ~]$ cc bank.c
[student@localhost ~]$ ./a.out
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2[student@localhost ~]$

Output
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2
9. Page Replacement program for FIFO
#include <stdio.h>
#include <stdbool.h>
bool isPageInFrame(int frame[], int fsize, int page) {
for (int i = 0; i < fsize; i++) {
if (frame[i] == page) {
return true;
} }
return false;}
int main() {
int n, f, i;
printf("Enter the number of pages: ");
scanf("%d", &n);
int pages[n];
printf("Enter the pages: ");
for(i=0; i<n; i++)
{ scanf("%d", &pages[i]); }
printf("Enter the frame size: ");
scanf("%d", &f);
int frame[f];
int hits = 0, faults = 0, index = 0;
for (int i = 0; i < f; i++)
{ frame[i] = -1; }
for (int i = 0; i < n; i++)
{
int pg = pages[i];
if (isPageInFrame(frame, f, pg))
{
hits++;
}
else
{
faults++;
frame[index] = pg;
index = (index + 1) % f;
}
printf("Frame: ");
for (int j = 0; j < f; j++) {
if (frame[j] != -1) {
printf("%d ", frame[j]);
}
else {
printf(". "); } }
printf("\n");
}
printf("Total hits: %d\n", hits);
printf("Total faults: %d\n", faults);
return 0;
}
Output:
Incoming Frame 1 Frame 2 Frame 3
4 4 - -
1 4 1 -
2 4 1 2
4 4 1 2
5 5 1 2
Total Page Faults: 4
10. Program to implement file organization techniques
#include<stdio.h>
#include<string.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir;
void main()
{
int i,ch;
char f[30];
dir.fcnt = 0;
printf("\nEnter name of directory -- ");
scanf("%s", dir.dname);
while(1)
{
printf("\n\n 1. Create File\t2. Delete File\t3. Search File \n 4. Display Files\t5. Exit\nEnter your
choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n Enter the name of the file -- ");

scanf("%s",dir.fname[dir.fcnt]);
dir.fcnt++;
break;
case 2: printf("\n Enter the name of the file -- ");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is deleted ",f);
strcpy(dir.fname[i],dir.fname[dir.fcnt-1]);
break; } }
if(i==dir.fcnt)
printf("File %s not found",f);
else
dir.fcnt--;
break;
case 3: printf("\n Enter the name of the file -- ");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{ if(strcmp(f, dir.fname[i])==0) {
printf("File %s is found ", f);
break;
}}
if(i==dir.fcnt)
printf("File %s not found",f);
break;
case 4: if(dir.fcnt==0)
printf("\n Directory Empty");
else
{
printf("\n The Files are -- ");
for(i=0;i<dir.fcnt;i++)
printf("\t%s",dir.fname[i]); }
break;
default: exit(0); } }
getch();
}
OUTPUT:
Enter name of directory -- CSE
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 1
Enter the name of the file -- A
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 1
Enter the name of the file -- B
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 1
Enter the name of the file -- C
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 4
The Files are -- A B C
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 3
Enter the name of the file – ABC

File ABC not found


1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 2
Enter the name of the file – B
File B is deleted
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 5
11. Sequential File allocation Techniques
#include<stdio.h>
#include<string.h>
struct file { char name[20]; int sb,nob; }f[30];
int main() {
int i,j,n;
char s[20];
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("\nEnter file name %d :",i+1);
scanf("%s",f[i].name);
printf("Enter starting block of file %d :",i+1);
scanf("%d",&f[i].sb);
printf("Enter no of blocks in file %d :",i+1);
scanf("%d",&f[i].nob); }
printf("\nEnter the file name to be searched -- ");
scanf("%s",s);
for(i=0;i<n;i++) {
if(strcmp(s, f[i].name)==0) break; }
if(i==n)
printf("\nFile Not Found");
else
{
printf("\nFILE NAME START BLOCK NO OF BLOCKS BLOCKS OCCUPIED\n");
printf("\n%s\t\t%d\t\t%d\t",f[i].name,f[i].sb,f[i].nob);
for(j=0;j<f[i].nob;j++)
printf("%d, ",f[i].sb+j);
}
return 0;
}

OUTPUT:
[student@localhost CD049]$ cc sfa.c
[student@localhost CD049]$ ./a.out
Enter no of files :3

Enter file name 1 :sample1


Enter starting block of file 1 :0
Enter no of blocks in file 1 :3

Enter file name 2 :sample2


Enter starting block of file 2 :5
Enter no of blocks in file 2 :4
Enter file name 3 :sample3
Enter starting block of file 3 :13
Enter no of blocks in file 3 :5
Enter the file name to be searched -- sample2
FILE NAME START BLOCK NO OF BLOCKS BLOCKS OCCUPIED
sample2 5 4 5, 6, 7, 8
12. FCFS Disk Scheduling algorithm
#include <stdio.h>
#include <math.h>
int size = 8;
void FCFS(int arr[],int head)
{
int seek_count = 0;
int cur_track, distance;
for(int i=0;i<size;i++)
{
cur_track = arr[i];
// calculate absolute distance
distance = fabs(head - cur_track);
// increase the total count
seek_count += distance;
// accessed track is now new head
head = cur_track; }
printf("Total number of seek operations: %d\n",seek_count); 29

printf("Seek Sequence is\n");


for (int i = 0; i < size; i++) {
printf("%d\n",arr[i]);
}}
int main()
{
int arr[8] = { 176, 79, 34, 60, 92, 11, 41, 114 };
int head = 50;
FCFS(arr,head);
return 0; }
Output:
Total number of seek operations = 510
Seek Sequence is
176
79
34
60
92
11
41
114

You might also like