You are on page 1of 62

KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Introduction to Operating System

A computer system can be divided into 4 components:


- Hardware (CPU, memory, input/output devices, etc.),
- Operating system
- System programs (word processors, spread sheets, accounting
software’s, compilers,)
- Application programs.
In 1960’s definition of
 An operating system is “software that controls the hardware”.
 An operating system is the programs that make the hardware useable.
 An operating system is the set of programs that controls a computer.
 An Operating system is software that creates a relation between the User,
Software and Hardware. It is an interface between the all. All the
computers need basic software known as an Operating System (OS) to
function.
The OS acts as an interface between the User, Application Programs, Hardware
and the System Peripherals. The OS is the first software to be loaded when a
computers starts up. The entire application programs are loaded after the OS.

Types of Operating System (Based of No. of user):


1. Single User: If the single user Operating System is loaded in computer’s
memory; the
computer would be able to handle one user at a time.
Ex: MS-Dos, MS-Win 95-98, Win-ME

2. Multi user: If the multi-user Operating System is loaded in computer’s


memory; the
computer would be able to handle more than one user at a time.
Ex: UNIX, Linux, XENIX

3. Network: If the network Operating System is loaded in computer’s memory;


the
computer would be able to handle more than one computer at time.
Ex: Novel Netware, Win-NT, Win-2000-2003

Command Prompt Interface:


Operating System provides a text based interface called command prompt. From
the

1
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

command prompt commands can be issued to perform file and disk management
and to run program. Results of these commands are presented to the user as text
message.
C:\>-The command prompt can be an alphabet followed by one colon (:), one
back slash (\), one greater than sign (>) and one blinking element called cursor
(_).

Operating Systems Types

1.Single- And Multi-Tasking Operating Systems


A single-tasking system can only run one program at a time, while a multi-
tasking
operating system allows more than one program to be running in concurrency.
This is achieved by time-sharing, dividing the available processor time between
multiple processes that are each interrupted repeatedly in time slices by a task-
scheduling subsystem of the operating system.
Multi-tasking may be characterized in preemptive and co-operative types. In
preemptive multitasking, the operating system slices the CPU time and dedicates
a slot to each of the programs. Unix-like operating systems, e.g., Solaris, Linux,
as well as AmigaOS support preemptive multitasking.

2.Single- And Multi-User Operating Systems


Single-user operating systems have no facilities to distinguish users, but may
allow multiple programs to run in tandem.
A multi-user operating system extends the basic concept of multi-tasking with
facilities that identify processes and resources, such as disk space, belonging to
multiple users, and the system permits multiple users to interact with the system
at the same time.

3.Time-sharing operating systems schedule tasks for efficient use of the


system and may also include accounting software for cost allocation of processor
time, mass storage, printing, and other resources to multiple users.

4.Distributed Operating Systems


A distributed operating system manages a group of distinct computers and
makes them appear to be a single computer. The development of networked
computers that could be linked and communicate with each other gave rise to
distributed computing. Distributed computations are carried out on more than
one machine. When computers in a group work in cooperation, they form a
distributed system.

5.Embedded Operating Systems


Embedded operating systems are designed to be used in embedded computer
systems.They are designed to operate on small machines like PDAs with less
autonomy. They are able to operate with a limited number of resources. They are
very compact and extremely efficient by design. Windows CE and “Minix 3”are
some examples of embedded operating systems.

6.Real-Time Operating Systems

2
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

A real-time operating system is an operating system that guarantees to process


events or data by a specific moment in time. A real-time operating system may
be single- or multi-tasking, but when multitasking, it uses specialized scheduling
algorithms so that a deterministic nature of behavior is achieved. An event-
driven system switches between tasks based on their priorities or external events
while time-sharing operating systems switch tasks based on clock interrupts

3
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex.No : 1 BASICS OF UNIX COMMANDS

Aim:
To Understand the basic commands of UNIX operating system.

Description:
Unix is a family of multitasking, multiuser computer operating systems that derive
from the original AT&T . Unix was designed to be portable, multi-tasking and multi-
user in a time-sharing configuration. Unix systems are characterized by various
concepts: the use of plain text for storing data; a hierarchical file system; treating
devices and certain types of inter-process communication (IPC) as files; and the use of
a large number of software tools, small programs that can be strung together through
a command-line interpreter using pipes, as opposed to using a single monolithic
program that includes all of the same functionality. The Unix Programming
Environment as "the idea that the power of a system comes more from the
relationships among programs than from the programs themselves. Unix, the operating
system consists of many utilities along with the master control program, the kernel.
The kernel provides services to start and stop programs, handles the file system and
other common "low-level" tasks that most programs share, and schedules access to
avoid conflicts when programs try to access the same resource or device
simultaneously. To mediate such access, the kernel has special rights, reflected in the
division between user space and kernel space. The microkernel concept was
introduced in an effort to reverse the trend towards larger kernels and return to a
system in which most tasks were completed by smaller utilities. 

I. Basic Commands:
1. Echo Command :
This command is used to print the arguments on the screen .
Syntax : $echo <text>
Multi line echo command :
To have the output in the same line , the following commands can be
used.
Syntax : $echo <text\>text
To have the output in different line, the following command can be used.
Syntax : $echo “text
>line2
>line3”
2. ’who’ Command :
It is used to display who are the users connected to our computer
currently.
Syntax : $who – option’s
Options : -
H–Display the output with headers.
b–Display the last booting date or time or when the system was lastly
rebooted.
3. ’who am i’ Command :
Display the details of the current working directory.
Syntax : $who am i
4. ’tty’ Command :
It will display the terminal name.

4
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Syntax : $tty
5. ’Binary’ Calculator Command :
It will change the „$‟ mode and in the new mode, arithmetic operations
such as +,-,*,/,%,n,sqrt(),length(),=, etc can be performed . This
command is used to go to the binary calculus mode.
Syntax :
$bc operations
^d
$
1 base –inputbase
0 base – outputbase are used for base conversions.
Base :
Decimal = 1 Binary = 2 Octal = 8 Hexa = 16

II. DIRECTORY RELATED COMMANDS :

1.Present Working Directory Command :


To print the complete path of the current working directory.
Syntax : $pwd
2.MKDIR Command :
To create or make a new directory in a current directory .
Syntax : $mkdir <directory name>
3.CD Command :
To change or move the directory to the mentioned directory .
Syntax : $cd <directory name.
4.RMDIR Command :
To remove a directory in the current directory & not the current directory
itself.
Syntax : $rmdir <directory name>

III. FILE RELATED COMMANDS :


1.CREATE A FILE :
To create a new file in the current directory we use CAT command.
Syntax :
$cat > <filename.
The > symbol is redirectory we use cat command.
2.DISPLAY A FILE :
To display the content of file mentioned we use CAT command without
„>‟ operator.
Syntax :
$cat <filename.
Options –s = to neglect the warning /error message.
3.COPYING CONTENTS :
To copy the content of one file with another. If file doesnot exist, a new
file is created and if the file exists with some data then it is overwritten.
Syntax :
$ cat <filename source> >> <destination filename>
$ cat <source filename> >> <destination filename> it is avoid
overwriting.
Options : -

5
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

-n content of file with numbers included with blank lines.


Syntax :
$cat –n <filename>
4.SORTING A FILE :
To sort the contents in alphabetical order in reverse order.
Syntax :
$sort <filename >
Option : $ sort –r <filename>
5.COPYING CONTENTS FROM ONE FILE TO ANOTHER :
To copy the contents from source to destination file . so that both
contents are same.
Syntax :
$cp <source filename> <destination filename>
$cp <source filename path > <destination filename path>
6.MOVE Command :
To completely move the contents from source file to destination file and
to remove the source file.
Syntax :
$ mv <source filename> <destination filename>
7.REMOVE Command :
To permanently remove the file we use this command .
Syntax :
$rm <filename>

8. WORD Command :
To list the content count of no of lines , words, characters .
Syntax :
$wc<filename>
Options :
-c – to display no of characters.
-l – to display only the lines.
-w – to display the no of words.

9. LIST Command :
It is used to list all the contents in the current working directory.
Syntax : $ ls – options <arguments>
If the command does not contain any argument means it is working in the
Current directory.
Options :
a– used to list all the files including the hidden files.
c– list all the files columnwise.
d- list all the directories.
m- list the files separated by commas.
p- list files include „/‟ to all the directories.
r- list the files in reverse alphabetical order.
f- list the files based on the list modification date.
x-list in column wise sorted order.

IV. DATA & CALENDER RELATED COMMANDS


1.Date Command :

6
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

This command is used to display the current data and time.


Syntax :
$date
$date +%ch
Options : -
a = Abbrevated weekday.
A = Full weekday.
b = Abbrevated month.
B = Full month.
c = Current day and time.
C = Display the century as a decimal number.
d = Day of the month.
D = Day in „mm/dd/yy‟ format
h = Abbreviated month day.
H = Display the hour.
L = Day of the year.
m = Month of the year.
M = Minute.
P = Display AM or PM
S = Seconds
T = HH:MM:SS format
u = Week of the year.
y = Display the year in 2 digit.
Y = Display the full year.
Z = Time zone .
To change the format :
Syntax :
$date „+%H-%M-%S‟
2.Calender Command :
This command is used to display the calendar of the year or the particular month
of calendar year.
Syntax :
a.$cal <year>
b.$cal <month> <year>
Here the first syntax gives the entire calendar for given year & the second Syntax gives
the calendar of reserved month of that year.

V. FILTERS AND PIPES


Description:
A filter is a small and (usually) specialized program in Unix-like operating
systems that transforms plain text (i.e., human readable) data in some
meaningful way and that can be used together with other filters and pipes to
form a series of operations that produces highly specific results.

1.HEAD : It is used to display the top ten lines of file.


Syntax: $head<filename>
2.TAIL : This command is used to display the last ten lines of file.
Syntax: $tail<filename>

7
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

3.PAGE : This command shows the page by page a screen full of information is
displayed after which the page command displays a prompt and passes for the
user to strike the enter key to continue scrolling.
Syntax: $ls –a\p
4. MORE : It also displays the file page by page .To continue scrolling with
more command , press the space bar key.
Syntax: $more<filename>
5.PIPE : It is a mechanism by which the output of one command can be
channeled into the input of another command.
Syntax: $who | wc-l

VI. SEARCHING AND SORTING COMMANDS


1. GREP :
This command is used to search and print the specified patterns from the file.
The ls command lists the contents of /sbin and pipes its output (using
the pipe operator, which is designated by the vertical bar character) to the
filter grep, which searches for all files and directories that contain the letter
sequence mk in their names. grep then pipes its output to the sort filter,
which, with its -r option, sorts it in reverse alphabetical order. sort, in turn,
pipes its output to the head filter. The default behavior of head is to read the
first ten lines of text or output from another command, but the -3 option here
tells it read only the first three. head thus writes the first three results from
sort (i.e., the last three filenames or directory names from /sbin that contain
the string mk) to the display screen.

Syntax: $grep [option] pattern <filename>

Description:
- grep command searches the given file for lines containing a match to the given
strings or words. By default, grep prints the matching lines. Use grep to search for
lines of text that match one or many regular expressions, and outputs only the
matching lines. The name, "grep", derives from the command used to perform a
similar operation, using the Unix/Linux text editor ed:
g/re/p

Syntax
grep 'word' filename
grep 'string1 string2' filename
cat otherfile | grep 'something'
command | grep 'something'

2. SORT : This command is used to sort the datas in some order.


Syntax: $sort<filename>

V. FILE PERMISSION COMMANDS

SYNTAX: $chmod mode filename


DESCRIPTION: This command is used to alter the access permissions for the owner
groups and others for a file.

8
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

MODES:
a) ABSOLUTE MODE:
SYNTAX: $chmod <octal representation> filename
DESCRIPTION: This mode uses number to alter permissions for a file or for
all the users.

OCTAL MEANING
4 Read permissions
2 Write
1 Execute
0 No permissions
Eg: $chmod 644 file.c
DESCRIPTION: Read and write to owner and read to groups and others.

b) SYMBOLIC MODE:
SYNTAX: $chmod <type of user><operation><access permission> filename
DESCRIPTION: This mode uses letters to alter permissions for a file and for
all users.

CHARATER- TYPE OF USER


u- denotes user or owner of the file
g- denotes group to which the user belongs to
o- denotes users excluding owner and members iroup
a- Denotes all users including owner, group and others.
CHARATER- ACCESS PERMISSION
r- sets read permission
w- sets write permission
v- sets execute permission
CHARATER- ACTION TO BE PERFORMED
+ assigns permissions for the specified user
- removes permission from the specified user
= Assign permission for the specified user
Eg: $chmod u+x file.c
DESCRIPTION: Assigns execute permission to user only. To check the access
permissions, use this command.
FOR Eg: ls.l file

VI. GENERAL PURPOSE COMMANDS:


SYNTAX: $who | wc
DESCRIPTION: This command first executes who and the result is transformed to
the input of word count command.
VII. COMMANDS FOR ‘vi’ EDITOR

DESCRIPTION :
The Vi editor is a visual editor used to create and edit text, files,
documents and programs. It displays the content of files on the screen and allows
a user to add, delete or change part of text . There are three modes available in
the Vi editor , they are
1.Command mode
2.Input (or) insert mode.

9
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

I.Starting Vi :
The Vi editor is invoked by giving the following commands in UNIX
prompt.
Syntax : $vi <filename> (or)
$vi
This command would open a display screen with 25 lines and with tilt (~)
symbol at the start of each line. The first syntax would save the file in the
filename mentioned and for the next the filename must be mentioned at the end.
Options :
1.vi +n <filename> - this would point at the nth line (cursor pos).
2.vi –n <filename> - This command is to make the file to read only to
change from one mode to another press escape key.

II.INSERTING AND REPLACING COMMANDS :


To move editor from command node to edit mode, you have to press the
<ESC> key. For inserting and replacing the following commands are used.
1.ESC a Command :
This command is used to move the edit mode and start to append after
the current character.
Syntax : <ESC> a
2.ESC A COMMAND :
This command is also used to append the file , but this command append
at the end of current line.
Syntax : <ESC> A
3.<ESC> j :
This command is used to move down a single line or a number of lines.
Syntax :
<ESC> j – single down movement.
<ESC> nj – „n‟ times down movement.
4.<ESC> k :
This command is used to move up a single line or a number of lines.
Syntax :
<ESC> k – single line above.
<ESC> nk – „n‟ lines above.
5.ENTER (OR) N ENTER :
This command will move the cursor to the starting of next lines or a
group of lines mentioned.
Syntax :
<ESC> enter <ESC> n enter.
6.<ESC> + Command :
This command is used to move to the beginning of the next line.
Syntax :
<ESC> + <ESC> n+
7.<ESC> - Command :
This command is used to move to the beginning of the previous line.
Syntax :
<ESC> - <ESC> n-
8.<ESC> 0 :
This command will bring the cursor to the beginning of the same current
line.

10
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Syntax :
<ESC> 0
9.<ESC> $ :
This command will bring the cursor to the end of the current line.
Syntax :
<ESC> $
10.<ESC> ^ :
This command is used to move to first character of first lines.
Syntax :
<ESC> ^
11.<ESC> b Command :
This command is used to move back to the previous word (or) a number
of words.
Syntax :
<ESC> b <ESC>nb
12.<ESC> e Command :
This command is used to move towards and replace the cursor at last
character of the word (or) no of words.
Syntax :
<ESC> e <ESC>ne
13.<ESC> w Command :
This command is used to move forward by a single word or a group of
words.
Syntax :
<ESC> w <ESC> nw
III. DELETING THE TEXT FROM Vi :
1.<ESC> x Command :
To delete a character to right of current cursor positions , this command
is used.
Syntax :
<ESC> x <ESC> nx
2.<ESC> X Command :
To delete a character to left of current cursor positions , this command is
used.
Syntax :
<ESC> X <ESC> nX
3.<ESC> dw Command :
This command is to delete a single word or number of words to right of
current cursor position.
Syntax :
<ESC> dw <ESC> ndw
4.db Command :
This command is to delete a single word to the left of the current cursor
position.
Syntax :
<ESC> db <ESC> ndb
5.<ESC> dd Command :
This command is used to delete the current line (or) a number of line
below the current line.
Syntax :

11
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

<ESC> dd <ESC> ndd


6.<ESC> d$ Command :
This command is used to delete the text from current cursor position to
last character of current line.
Syntax : <ESC> d$

IV.SAVING AND QUITING FROM vi :-


1.<ESC> w Command :
To save the given text present in the file.
Syntax : <ESC> : w
2.<ESC> q! Command :
To quit the given text without saving.
Syntax : <ESC> :q!
3.<ESC> wq Command :
This command quits the vi editor after saving the text in the mentioned
file.
Syntax : <ESC> :wq
4.<ESC> x Command :
This command is same as „wq‟ command it saves and quit.
Syntax : <ESC> :x
5.<ESC> q Command :
This command would quit the window but it would ask for again to save
the file.
Syntax : <ESC> : q

Result:
Thus the basic commands of UNIX operating system has been successfully
practiced.

VIVA QUESTIONS
1. What is UNIX?
2. What are filters?
3. What is Kernel?
4. What is an operating system?
5. List the types of operating system?
6. Give some example os for wireless devices.
7. What is a bootstrap program?
8. What is BIOS?
9. What are system calls?
10. How to open a file in read only mode in vi editor?

12
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

EX NO: 2a Implementation of directory management using the


following system calls of UNIX operating system: fork, exec, get id, exit, w it,
close, stat.

AIM:
To write a program for implementing Directory management using the following
system calls of UNIX operating system: opendir, readdir.

ALGORITHM:
1. Start the program.
2. Read the input from the command line.
3. Declare the pid and get the pid by using the getpid() method. execlp() system
call used to execute specified command.
4. Create a child process by calling the fork() system call.Open the directory at
specified in command line input.
5. Check if(pid==0) then print the child process id and if(pid==1) then print the
parent process value. Otherwise print fork failed.
6. Check if pid==0 then execute the ‘ls’ command and display the list of files and
dir.
7. Stop the program.

OUTPUT:
before fork 4258
thisline from child,
the child process id 4259
a.out
ch.c
come.c
data
file1.c
file2.c
first.c
fit.c
sysytem.c
before fork 4258

RESULT:
Thus the process system call program was executed and verified successfully.

EX NO:2 (b) Implementation of directory management using the


following system calls of UNIX operating system: opendir, readdir.

AIM:

To write a program for implementing Directory management using the following


system calls of UNIX operating system: opendir, readdir.

ALGORITHM:

13
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

1. Start the program.


2. Open the directory at specified in command line input.
3. Display the directory contents.
4. Stop the program.

OUTPUT:

[root@localhost ~]# cc dr.c

[root@localhost ~]# ./a.out lab_print

NAME OF ITEM
pri_output.doc
sjf_output.doc
fcfs_output.doc
rr_output.doc
ipc_pipe_output.doc
pro_con_prob_output.doc
TOTAL NUMBER OF ITEM IN THAT DIRECTORY IS 8

RESULT:

Thus the program for directory management was written and successfully
executed.

VIVA QUESTIONS

14
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

EX NO:3 Write a programs to simulate UNIX commands like ls, grep, etc.

AIM:
To write a program to simulate UNIX commands like ls, grep, etc.

ALGORITHM:
1. Start the program.
2. Read the input through command line.
3. Open the specified file.
4. Options (c & i) are performed.
5. Stop the program.

OUTPUT:
[root@localhost ~]# cat tst sd
dsaASD[root@localhost ~]# ./a.out -i a tst
aA[root@localhost ~]# ./a.out -c a tst 1[root@localhost ~]# ./a.out -c A tst
1[root@localhost ~]# ./a.out -c sd tst 1[root@localhost ~]# ./a.out -c s tst 2

RESULT:
Thus the program to stimulate the UNIX commands was written and successfully
executed.

VIVA QUESTIONS

15
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex.No : 4 SHELL PROGRAMMING

Aim:
Write the shell program to compare two strings, to find the greatest of three
numbers, Fibonacci series and to perform the arithmetic operations using switch
case.

Description:
A Shell offers a user an interface with the OS kernel. A user obtains OS services
through an OS shell. When a user logs in, he has a login shell. The login shell offers
the first interface that the user interacts with either as a terminal console, or through a
window interface which emulates a terminal. A shell is essentially a process which is a
command interpreter. Every Unix shell offers two key facilities. In addition to an
interactive command interpreter, it also offers a very useful programming
environment. The shell programming environment accepts programs written in shell
programming language. In later sections in this chapter we shall learn about the shell
programming language and how to make use of it for enhancing productivity. A user
obtains maximum gains when he learns not only to automate a sequence of commands
but also to make choices within command sequences and invoke repeated executions.

Ex.No: 4.a) COMPARISON OF TWO STRINGS

Aim:
To write a shell program to compare two strings.

Algorithm:
1. Start the program
2. Enter into the vi editor and go to the insert mode for entering the code.
3. Read the first string.
4. Read the second string .
5. Compare the two strings using the if loop
6. If the condition satisfies then print that two strings are equal else print two
strings are not equal.

16
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

7. Save and exit from the vi editor by using ‘:wq!’


8. Execute the program by ./filename.sh.
9. Stop the program.

Sample I/P: 1
Enter first string: hai
Enter second string: hai
Sample O/P:1
The two strings are equal
Sample I/P:2
Enter first string: hai
Enter second string: cse
Sample O/P:2
The two strings are not equal

Result:
Thus the shell program to compare the two strings has been executed and output is
verified successfully.

Ex.No: 4.b) MAXIMUM OF THREE NUMBERS


Aim:
To write a shell program to find maximum of three numbers.

Algorithm:
1. Start the program
2. Enter into the vi editor and go to the insert mode for entering the code.
3. Read three variables A,B,C.
4. Check if A is greater than B and C.
5. If so print A is greater.
6. Else check if B is greater than C.
7. If so print B is greater.
8. Else print C is greater.
9. Save and exit from the vi editor by using ‘:wq!’
10. Execute the program by ./filename.sh.
11. Stop the program.

Sample I/P:
Enter A:23
Enter B:45
Enter C:67
Sample O/P: C is greater
Result:
Thus the shell program to find the maximum of three numbers has been executed
and output is verified successfully.

Ex. No: 4.c) FIBONACCI SERIES


Aim:
To write a shell program to generate Fibonacci series.

Algorithm :

17
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

1. Start the program


2. Enter into the vi editor and go to the insert mode for entering the code.
3. Initialize a to 0 and b to 1.
4. Print the values of 'a' and 'b'
5. Add the values of 'a' and 'b'. Store the added value in variable 'c'.
6. Print the value of 'c'.
7. Initialize 'a' to 'b' and 'b' to 'c'.
8. Repeat the steps 5,6,7 till the value of 'i' is less than or equal to ‘n’.
9. Save and exit from the vi editor by using ‘:wq!’
10. Execute the program by ./filename.sh.
11. Stop the program.

Sample I/P :
Enter the no: 5
Sample O/P:
0
1
1
2
3
5
Result :
Thus the shell program to find the Fibonacci series has been executed and
output is verified successfully.

Ex. No: 4.d) ARITHMETIC OPERATIONS USING SWITCH CASE


Aim:
To write a shell program to perform the arithmetic operations using
switchcase.
Algorithm :
1. Start the program
2. Enter into the vi editor and go to the insert mode for entering the code.
3. Read the input variables and assign the value.
4. Print the various arithmetic operations which we are going to perform.
5. Using the case operator assign the various functions for the arithmetic
operators.
6. Check the values for all the corresponding operations.
7. Print the result .
8. Save and exit from the vi editor by using ‘:wq!’
9. Execute the program by ./filename.sh.
10. Stop the program.

Sample I/P :
1.Addition
2.Subraction
3.Multiplication
4.Division
Enter your choice:1
Enter the value of b:3
Enter the value of c:4

18
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

b is 3 c is 4
the sum is 7
Sample O/P:
b is 3 c is 4
the sum is 7

Result :
Thus the shell program to perform arithmetic operations using switch case has
been executed and the output is verified successfully.

VIVA QUESTIONS
1. What is shell programming?
2. What are shell variables?
3. What is Bash Shell?
4. What is a superuser?
5. Is UNIX open source?
6. Which language is used in the design of UNIX OS?
7. Which command can be used to alter the file access permissions?
8. Which command can be used to delete a shell variable?
9. Which shell variable holds the shell script file name?
10. Is it compulsory to have the extension ‘sh’ for a shell script?

19
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex. No: 5 IMPLEMENTATION OF SCHEDULING ALGORITHMS


Aim:
To write the C program for the implementation of CPU scheduling algorithms
for
a) Round robin scheduling.
b) Shortest Job First (SJF) scheduling.
c) First Come First Serve scheduling.
d)Priority scheduling.
Description:
CPU scheduling is a process which allows one process to use the CPU while the
execution of another process is on hold(in waiting state) due to unavailability of
any resource like I/O etc, thereby making full use of CPU. The aim of CPU
scheduling is to make the system efficient, fast and fair.
Whenever the CPU becomes idle, the operating system must select one of the
processes in the ready queue to be executed. The selection process is carried out
by the short-term scheduler (or CPU scheduler). The scheduler selects from
among the processes in memory that are ready to execute, and allocates the CPU
to one of them. There are two scheduling schemes Non-preemptive and
Preemptive scheduling. Under non-preemptive scheduling, once the CPU has
been allocated to a process, the process keeps the CPU until it releases the CPU
either by terminating or by switching to the waiting state. In Preemptive
Scheduling, the tasks are usually assigned with priorities. At times it is necessary
to run a certain task that has a higher priority before another task although it is
running. Therefore, the running task is interrupted for some time and resumed
later when the priority task has finished its execution.
Scheduling criteria:
There are many different criterias to check when considering the "best"
scheduling algorithm :
 CPU utilization
To make out the best use of CPU and not to waste any CPU cycle, CPU
would be working most of the time(Ideally 100% of the time). Considering a
real system, CPU usage should range from 40% (lightly loaded) to 90%
(heavily loaded.)
 Throughput
It is the total number of processes completed per unit time or rather say total
amount of work done in a unit of time. This may range from 10/second to
1/hour depending on the specific processes.
 Turnaround time
It is the amount of time taken to execute a particular process, i.e. The
interval from time of submission of the process to the time of completion of
the process(Wall clock time).
 Waiting time
The sum of the periods spent waiting in the ready queue amount of time a
process has been waiting in the ready queue to acquire get control on the
CPU.
 Load average
It is the average number of processes residing in the ready queue waiting for
their turn to get into the CPU.
 Response time

20
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Amount of time it takes from when a request was submitted until the first
response is produced. Remember, it is the time till the first response and not
the completion of process execution(final response).

Round Robin(RR) Scheduling


 A fixed time is allotted to each process, called quantum, for execution.
 Once a process is executed for given time period that process is preempted and
other process executes for given time period.
 Context switching is used to save states of preempted processes.

Shortest-Job-First(SJF) Scheduling
 Shortest job first (SJF) or shortest job next, is a scheduling policy that selects
the waiting process with the smallest execution time to execute next. SJN is a
non-preemptive algorithm.

First Come First Serve(FCFS) Scheduling


 Jobs are executed on first come, first serve basis.
 Poor in performance as average wait time is high.

21
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Priority Scheduling
 Priority is assigned for each process.
 Process with highest priority is executed first and so on.
 Processes with same priority are executed in FCFS manner.
 Priority can be decided based on memory requirements, time requirements or
any other resource requirement.

Ex No: 5.a) ROUND ROBIN SCHEDULING


Aim:
Write a C program to implement the Round Robin CPU scheduling algorithm to
find turnaround time and waiting time.

Algorithm
1. Start the program.
2.Accept the number of processes in the ready Queue and time quantum (or)
time slice
3.For each process in the ready Q, assign the process id and accept the CPU
burst time
4.Calculate the no. of time slices for each process where
No. of time slice for process(n) = burst time process(n)/time slice
5.If the burst time is less than the time slice then the no. of time slices =1.
6. Consider the ready queue is a circular Q, calculate

22
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

(a) Waiting time for process(n) = waiting time of process(n-1)+ burst


time of process(n-1 ) + the time difference in getting the CPU from
process(n-1)
(b) Turn around time for process(n) = waiting time of process(n) + burst
time of process(n)+ the time difference in getting CPU from
process(n).
7.Calculate
(a) Average waiting time = Total waiting Time / Number of process
(b) Average Turnaround time = Total Turnaround Time / Number of
process
8.Stop the process.

OUTPUT:
Enter the number of Processors
4
Enter Arrival Time and Burst Time for Process Process Number 1: 0
9
Enter Arrival Time and Burst Time for Process Process Number 2: 1
5
Enter Arrival Time and Burst Time for Process Process Number 3: 2
3
Enter Arrival Time and Burst Time for Process Process Number 4: 3
4
Enter the quantum
5

ROUND ROBIN SCHEDULING ALGORITHM

Process Turn around Time Waiting Time

P[ 2] 9 4

P[3] 10 8

P[4] 14 10

P[1] 21 12

The average Waiting Time = 8.50000


The average Turn around Time = 13.75000
Result:
Thus the C program to implement Round Robin scheduling was written
and waiting time and turnaround time was calculated successfully.

Ex. No: 5(b) SHORTEST JOB FIRST SCHEDULING

Aim:
Write a C program to implement the Shortest Job First (SJF)CPU
scheduling algorithm to find turnaround time and waiting time.

23
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Algorithm:
1.Start the program
2.Accept the number of processes in the ready Queue. Assume that all process
arrive at same time.
3.For each process in the ready Q, assign the process id and accept the CPU
burst time
4. Start the Ready Q according the shortest Burst time by sorting according to
lowest to highest burst time.
5. Set the waiting time of the first process as ‘0’ and its turnaround time as its
burst time.
6. For each process in the ready queue, calculate
(a) Waiting time for process(n)= waiting time of process (n-1) + Burst
time of process(n-1)
(b) Turn around time for Process(n)= waiting time of Process(n)+ Burst
time for process(n)
7.Calculate
(c) Average waiting time = Total waiting Time / Number of process
(d) Average Turnaround time = Total Turnaround Time / Number of
process
8.Stop the program.

OUTPUT:
Enter number of process 3

Enter the Burst Time of Process 04


Enter the Burst Time of Process 13
Enter the Burst Time of Process 25
SHORTEST JOB FIRST SCHEDULING ALGORITHM
PROCESS ID BURST TIME WAITING TIME TURNAROUND TIME

1 3 0 3

0 4 3 7

2 5 7 12

AVERAGE WAITING TIME = 3.33


AVERAGE TURN AROUND TIME = 7.33
Result:
Thus the C program to implement Shortest Job First scheduling was
written and waiting time and turnaround time was calculated successfully.

Ex. No: 5(c) FIRST COME FIRST SERVE SCHEDULING


Aim:
Write a C program to implement the First Come First Serve (FCFS) CPU
scheduling algorithm to find turnaround time and waiting time.

Algorithm:
1.Start the program

24
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

2. Accept the number of processes in the ready Queue. Assume that all process
arrive at same time.
3. For each process in the ready Q, assign the process id and accept the CPU
burst time
4. Set the waiting of the first process as ‘0’ and its burst time as its turn around
time
5. for each process in the Ready Q calculate
(c) Waiting time for process(n)= waiting time of process (n-1) + Burst
time of process(n-1)
(d) Turn around time for Process(n)= waiting time of Process(n)+ Burst
time for process(n)
6. Calculate
(e) Average waiting time = Total waiting Time / Number of process
(f) Average Turnaround time = Total Turnaround Time / Number of
process
7. Stop the program.

OUTPUT:

Enter number of processors: 3


Enter the Burst Time of the process 1: 2
Enter the Burst Time of the process 2: 5
Enter the Burst Time of the process 3: 4

FIRST COME FIRST SERVE SCHEDULING ALGORITHM


Process ID Waiting Time Turn Around Time
1 0 2

2 2 7

3 7 11

Average Waiting Time 3.00


Average Turnaround Time 6.67
Result:
Thus the C program to implement First Come First Serve scheduling was
written and waiting time and turnaround time was calculated successfully.

Ex. No: 5.d) PRIORITY SCHEDULING


Aim:
Write a C program to implement the Priority CPU scheduling algorithm
to find turnaround time and waiting time.
Algorithm:
1. Start the program.
2. Accept the number of processes in the ready Queue. Assume that all process
arrives at same time.
3. For each process in the ready Q, assign the process id ,accept the CPU burst
time and priority for the processes.

25
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

4. Sort the ready queue according to the priority number.


5. Set the waiting of the first process as ‘0’ and its burst time as its turn around
time
6. For each process in the Ready Q calculate Waiting time for process(n)=
waiting time of process (n-1) + Burst time of process(n-1)
Turn around time for Process(n)= waiting time of Process(n)+ Burst time for
process(n)
7.Calculate Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process
8.Stop the program.

OUTPUT:
-----------PRIORITY SCHEDULING--------------
Enter the No of Process: 4
Enter the Burst time of Pid 0 : 2
Enter the Priority of Pid 0 : 3
Enter the Burst time of Pid 1 : 6
Enter the Priority of Pid 1 : 2
Enter the Burst time of Pid 2 : 4
Enter the Priority of Pid 2 : 1
Enter the Burst time of Pid 3 : 5
Enter the Priority of Pid 3 : 7
----------------------------------------------------------------------------------------
Pid Priority Burst time WaitingTime TurnArroundTime
----------------------------------------------------------------------------------------

2 1 4 0 4
1 2 6 4 10
0 3 2 10 12
3 7 5 12 17

Avg.Waiting Time: 6.500000


Avg.Turn Around Time: 10.750000

Result :
Thus the C program to implement Priority scheduling was written and
waiting time and turnaround time was calculated successfully.

VIVA QUESTIONS
1. What is First-Come-First-Served (FCFS) Scheduling?
2. Why CPU scheduling is required?
3.Which technique was introduced because a single job could not keep both the
CPU and the I/O devices busy?
a) Time-sharing b) SPOOLing c) Preemptive scheduling d) Multiprogramming
4. CPU performance is measured through ________.
a) Throughput b) MHz c) Flaps d) None of the above
5. Which of the following is a criterion to evaluate a scheduling algorithm?
a)CPU Utilization: Keep CPU utilization as high as possible.

26
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

b)Throughput: number of processes completed per unit time.


c) Waiting Time: Amount of time spent ready to run but not running.
d) All of the above
6.The optimum CPU scheduling algorithm is
a)FIFO b)SJF with preemption. c)SJF without preemption. d)Round Robin.
7. In terms of average wait time the optimum scheduling algorithm is
a)FCFS b)SJF c)Priority d)RR
8.What are the dis-advantages of SJF Scheduling Algorithm?
9. What are the advantages of SJF Scheduling Algorithm?
10. Define CPU Scheduling algorithm?
11.Round Robin scheduling is used in
a)Disk scheduling. b)CPU scheduling c)I/O scheduling. d)Multitasking
12. What are the dis-advantages of RR Scheduling Algorithm?
13.What are the advantages of RR Scheduling Algorithm?
14.Super computers typically employ _______.
a)Real time Operating system b) Multiprocessors OS c) desktop OS d) None of
the above
15. An optimal scheduling algorithm in terms of minimizing the average waiting
time of a given set of processes is ________.
a) FCFS scheduling algorithm b) Round robin scheduling algorithm
c) Shortest job - first scheduling algorithm d) None of the above
16. Priority CPU scheduling would most likely be used in a _____________ os.
17. Cpu allocated process to ___________________ priority.
18. calculate avg waiting time=
19. Maximum CPU utilization obtained with _________________________
20. Using _______________algorithms find the min & max waiting time.

27
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex. No. 6 IMPLEMENT SEMAPHORES

AIM:
Write a C program to implement producer/consumer problem using semaphore.
Description:
A semaphore is a data structure used to help threads work together without
interfering with each other. Mutual exclusion on the semaphore is enforced
within P(S) and V(S). If a number of processes attempt P(S) simultaneously,
only one process will be allowed to proceed & the other processes will be
waiting.
P(S) or wait(S):
If S > 0 then
Set S to S-1
Else
Block the calling process (i.e. Wait on S)

V(S) or signal(S):
If any processes are waiting on S
Start one of these processes
Else
Set S to S+1
Semaphores are of two types −
1. Binary semaphore
2. Counting semaphore
Binary semaphore can take the value 0 & 1 only. Counting semaphore can take
nonnegative integer values.
Producer consumer problem
Producer consumer problem is also known as bounded buffer problem. In this
problem we have two processes, producer and consumer, who share a fixed size
buffer. Producer work is to produce data or items and put in buffer. Consumer
work is to remove data from buffer and consume it. We have to make sure that
producer do not produce data when buffer is full and consumer do not remove
data when buffer is empty.

Algorithm:
1. Start the program.
2. Define producer() and consumer() and declare the variables
mutex=1,full=0,empty=3
3. Read the value for switch case to decide the operation.
4. If mutex=1 & empty!=0, the producer posts to the empty buffer semaphore.
5. This will increment its value, and if it were 0 it would wake up consumer threads
waiting on that semaphore.
6. The consumer thread that waits on that semaphore, upon waking up it will
decrement the value of the semaphore.
7. The empty buffer semaphore basically follows up with the buffer index.
8. The full buffer semaphore does the opposite.
9. The Consumer threads post to it when they dequeue from the buffer, which
increments the semaphore value.

28
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

10.The producer threads wait in them, which means they sleep if buffer is full, and
decrement the semaphore value each time they add element to buffer.
11.A mutex is used to protect access to buffer.
12. Stop the program.

Output:
1.Producer
2.Consumer
3.Exit
Enter your choice:1
Producer produces the item 1
Enter your choice:2
Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:1
Producer produces the item 1
Enter your choice:1
Producer produces the item 2
Enter your choice:1
Producer produces the item 3
Enter your choice:1
Buffer is full!!
Enter your choice:3

Result:
Thus the C program to implement producer consumer problem using
semaphore has been executed and verified successfully.
VIVA QUESTIONS
1. What is a semaphore?
2. What are the kinds of semaphore?
3. What integer values a binary semaphore has?
4. Semaphores are mostly used to implement :
a)System calls
b) IPC mechanisms
c) System protection
d) None of the mentioned
5. Spinlocks are intended to provide __________ only.
a) Mutual Exclusion
b) Bounded Waiting
c) Aging
d) Progress
6. What is mutex?
7. What is the difference between mutex and semaphore?
8. Are binary semaphore and mutex same?
9. What is a mutex and critical section?
10. Can a mutex be locked more than once?

29
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex. No: 7 IMPLEMENT SHARED MEMORY AND INTER PROCESS


COMMUNICATION (IPC)
Aim:
Write a C program to implement Inter Process Communication (IPC) using
shared memory.
Description:
Interprocess communication(IPC) is the transfer of data among different  processes.
There are five types of IPC.
1.Pipes
2.FIFO-also known as Named pipes 
3.Shared Memory
4.Message Queue
5.Semaphore
PIPES:
Pipes are used for unidirectional communication of related process only. The
limitation of the data to be passed.The capacity of data to be sent through pipes
are limited. The output of one pipe can be given as an input of another pipe. It is not
necessary to free them after the process has been finished.

FIFO(NAMED PIPES):
The solution to problem in pipes is given by means of named pipes. The
communication can be done between unrelated processes. It can be bi-
directional as well. One more difference between pipes and named pipes is that
the capacity of data that is the amount of data flow through a pipe during
execution.

SHARED MEMORY:
As the name implies, the same area of the physical memory is shared by one or
more processes. This memory segment is mapped into virtual memory spaces.
In shared memory two or more process can access the same memory segment.
Consider there are three process p1, p2 and p3. Processes p1 and p2 are
accessing the segment in read mode, and p3 in write mode. If p3 makes any
changes to the data, then it is automatically updated for the process p1 and p2
also. 
The advantage of shared memory is Shared memory provides fastest
mechanism of communication than the others. The process can read or write
without using any system call.
The disadvantage of shared memory is it does not benefit from the protection
that the operating system normally provides.
MESSAGE QUEUE:
The message queue also provides the way for unrelated processes to
communicate with each other. Comparing with other IPC mechanisms this
provides the easiest way of communication than others. Instead of sending data
one by one, it sends block of data. This is the difference between the pipes and
message queue. The difference between message queue and named pipes is that
the messages in the queue can be prioritized which cannot be done in the later.
As message queues are attached with the kernel, whenever a message is sent or
received it has to visit the kernel, which makes the communication slow.
Because of this, the communication process is little bit slower than the shared
memory.

30
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

SEMAPHORE:
In a multi-user or multiprocessing systems, there is a problem to have an exclusive
access over the shared resource. But it is difficult to write code to ensure the exclusive
access to a particular resource.
Algorithm:
1.Start the program.
2. In terminal change directory using : cd /home/exam1/Tc
3. Four child process were created under the parent process IPC.C
4. Communication between child Process is established through pipe.
5.Create a text file before executing IPC program using cat >filename
6.Command to compile : g++ filename.c -o filename
7.Command to execute: ./filename textfilname
8.Stop the program.

Output:
WORD COUNT: 8
CHARACTER COUNT: 67
SENTENCE COUNT : 0
LINE COUNT: 5

Result:
Thus the Inter process communication using shared memory has been
implemented successfully and the output was verified.
VIVA QUESTIONS
1. What is IPC?
2. List out the IPC techniques.
3. What is shared memory?
4. List the advantages and disadvantages of shared memory.
5. List the advantages and disadvantages of pipes.
6. List the advantages and disadvantages of message queue.
7. List the advantages and disadvantages of semaphore
8. List the advantages and disadvantages of named pipes.
9. The link between two processes P and Q to send and receive messages is
called :
a) communication link
b) message-passing link
c) synchronization link
10. In indirect communication between processes P and Q :
a) there is another process R to handle and pass on the messages between
P and Q
b) there is another machine between the two processes to help
communication
c) there is a mailbox to help communication between P and Q

31
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex. No: 8 BANKER’S ALGORITHM

Aim:
Write a C program to implement deadlock avoidance & Prevention by
using Banker’s Algorithm.

Description:
Banker’s Algorithm
When a new process enters a system, it must declare the maximum
number of instances of each resource type it needed. This number may exceed
the total number of resources in the system. When the user request a set of
resources, the system must determine whether the allocation of each resources
will leave the system in safe state. If it will the resources are allocation;
otherwise the process must wait until some other process release the resources.

Data structures
 n-Number of process, m-number of resource types.
 Available: Available[j]=k, k – instance of resource type Rj is available.
 Max: If max[i, j]=k, Pi may request at most k instances resource Rj.
 Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource
Rj
 Need: If Need[I, j]=k, Pi may need k more instances of resource type Rj,
Need[I, j]=Max[I, j]-Allocation[I, j];
Safety Algorithm
1. Work and Finish be the vector of length m and n respectively,
Work=Available and Finish[i] =False.
2. Find an i such that both
 Finish[i] =False
 Need<=Work
If no such I exists go to step 4.
3. work=work+Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.

Resource request algorithm


Let Request i be request vector for the process Pi, If request i=[j]=k, then
process Pi wants k instances of resource type Rj.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the
resources are available.
3. Have the system pretend to have allocated the requested resources to
process Pi by modifying the state as follows;
Available=Available-Request I;
Allocation I =Allocation+Request I;
Need i=Need i-Request I;
If the resulting resource allocation state is safe, the transaction is completed and
process Pi is allocated its resources. If the state is unsafe, the Pi must wait for
Request i and the old resource-allocation state is restored.

ALGORITHM:
1. Start the program.

32
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

2. Get the number of processes and values of resources needed for each
process.
3. Get the available value of resources.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. Stop the program.

OUTPUT:

//TEST CASE 1:
ENTER THE NO. OF PROCESSES:4
ENTER THE NO. OF RESOURCES:3
PROCESS 1
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:1
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:0
PROCESS 2
MAXIMUM VALUE FOR RESOURCE 1:6
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:3
ALLOCATED FROM RESOURCE 1:5
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 3
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:4
ALLOCATED FROM RESOURCE 1:2
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 4
MAXIMUM VALUE FOR RESOURCE 1:4
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:0
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:2
ENTER TOTAL VALUE OF RESOURCE 1:9
ENTER TOTAL VALUE OF RESOURCE 2:3
ENTER TOTAL VALUE OF RESOURCE 3:6

RESOURCES ALLOCATED NEEDED TOTAL AVAIL


P1 322 100 222 936 112
P2 613 511 102

33
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

P3 314 211 103


P4 422 002 420

AVAIL BEFORE AVAIL AFTER


P2 010 623
P1 401 723
P3 620 934
P4 514 936

THE ABOVE SEQUENCE IS A SAFE SEQUENCE

Result:
Thus the C program to implement deadlock avoidance and Prevention
by using Banker’s Algorithm was executed and the output is verified
successfully.
VIVA QUESTIONS
1. What is deadlock?
2. What is safe state?
3. A state is safe, if :
a) the system does not crash due to deadlock occurrence
b) the system can allocate resources to each process in some order and
still avoid a deadlock
c) the state keeps the system protected and safe
d) all of the mentioned
4.  A system is in a safe state only if there exists a :
a) safe allocation b) safe resource
c) safe sequence d) all of the mentioned
5. All unsafe states are :
a) deadlocks b) not deadlocks
c) fatal d) none of the mentioned
6. If no cycle exists in the resource allocation graph :
a) then the system will not be in a safe state b) then the system will be in
a safe state
c) all of the mentioned d) none of the mentioned
7. The Banker’s algorithm is _____________ than the resource allocation
graph algorithm.
a) less efficient b) more efficient
c) equal d) none of the mentioned
8. The data structures available in the Banker’s algorithm are :
a) Available b) Need
c) Allocation d) All of the mentioned
9. The content of the matrix Need is :
a) Allocation – Available b) Max – Available
c) Max – Allocation d) Allocation – Max
10. The resource allocation graph is not applicable to a resource allocation
system :
a) with multiple instances of each resource type b) with a single instance
of each resource type
c) single & multiple instance of each resource type d) none of the mentio

34
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex.No: 9 DEAD LOCK DETECTION

Aim:
Write a C program to implement deadlock detection.
Description:
Deadlock Definition:
A set of processes is deadlocked if each process in the set is waiting for an event
that only another process in the set can cause (including itself).Waiting for an
event could be:
 waiting for access to a critical section
 waiting for a resource Note that it is usually a non-preemptable
(resource).

Conditions for Deadlock :


 Mutual exclusion: resources cannot be shared.
 Hold and wait: processes request resources incrementally, and hold on to
What they've got.
 No preemption: resources cannot be forcibly taken from processes.
 Circular wait: circular chain of waiting, in which each process is waiting
for a resource held by the next process in the chain.
Strategies for dealing with Deadlock :
 ignore the problem altogether
 detection and recovery
 avoidance by careful resource allocation
 prevention by structurally negating one of the four necessary conditions.
Deadlock Prevention :
Difference from avoidance is that here, the system itself is built in such a way
that there are no deadlocks. Make sure atleast one of the 4 deadlock conditions is
never satisfied. This may however be even more conservative than deadlock
avoidance strategy.

ALGORITHM:
1.Start the program.
2.Initialize vectors of length m and n. Initialize
(a) Work = Available
(b) For i = 1,2, …, n, if Allocation i ≠ 0, then Finish[i] = false; otherwise,
Finish[i] = true.
3. Find an index i such that both:
(a) Finish[i] == false
(b) Requesti ≤ Work If no such i exists, go to step 4.
3.Work = Work + Allocationi Finish[i] = true go to step 2.
4. If Finish[i] == false, for some i, 1 ≤ i ≤ n, then the system is in deadlock state.
Moreover, if Finish[i] == false, then Pi is deadlocked.
5.Stop the program.

Output:
enter total no. of processes : 4
enter claim matrix :
01001

35
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

00101
00001
10101
enter allocation matrix :
10110
11000
00010
00000
enter resource vector :
21121
enter the availability vector :
00001

deadlock causing processes are : 1 2

Result:
Thus the C program to implement deadlock detection was executed and
the output is verified successfully.

VIVA QUESTIONS
1. The wait-for graph is a deadlock detection algorithm that is applicable when
a) all resources have a single instance b) all resources have multiple
instances
c) all resources have a single 7 multiple instance d) all of the mentioned
2.  An edge from process Pi to Pj in a wait for graph indicates that :
a) Pi is waiting for Pj to release a resource that Pi needs
b) Pj is waiting for Pi to release a resource that Pj needs
c) Pi is waiting for Pj to leave the system
d) Pj is waiting for Pi to leave the system
3. If the wait for graph contains a cycle :
a) then a deadlock does not exist b) then a deadlock exists
c) then the system is in a safe state d) either deadlock exists or system is in a
safe state
4. If deadlocks occur frequently, the detection algorithm must be invoked
________
a) rarely b) frequently c) rarely & frequently d) none of the mentioned
5. The disadvantage of invoking the detection algorithm for every request is :
a) overhead of the detection algorithm due to consumption of memory
b) excessive time consumed in the request to be allocated memory
c) considerable overhead in computation time
d) all of the mentioned
6. A deadlock eventually cripples system throughput and will cause the CPU
utilization to ______
a) increase b) drop c) stay still d) none of the mentioned
7. Every time a request for allocation cannot be granted immediately, the
detection algorithm is invoked. This will help identify :
a) the set of processes that have been deadlocked b) the set of processes in
the deadlock queue
c) the specific process that caused the deadlock d) all of the mentioned

36
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

8. A computer system has 6 tape drives, with ‘n’ processes competing for them.
Each process may need 3 tape drives. The maximum value of ‘n’ for which
the system is guaranteed to be deadlock free is :
a) 2 b) 3 c) 4 d) 1
9. A system has 3 processes sharing 4 resources. If each process needs a
maximum of 2 units then, deadlock :
a) can never occur b) may occur
c) has to occur d) none of the mentioned
10. ‘m’ processes share ‘n’ resources of the same type. The maximum need of
each process doesn’t exceed ‘n’ and the sum of all their maximum needs is
always less than m+n. In this setup, deadlock :
a) can never occur b) may occur
c) has to occur d) none of the mentioned

37
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex.No.10 IMPLEMENTATION OF THREADING & SYNCHRONIZATION


APPLICATIONS
Aim:
Write a C program to implement threading and synchronization
applications.
Description:
A thread is a flow of execution through the process code, with its own program
counter that keeps track of which instruction to execute next, system registers
which hold its current working variables, and a stack which contains the
execution history. A thread is also called a lightweight process.
When multiple threads of control share the same memory, we need to make sure
that each thread sees a consistent view of its data. If each thread uses variables
that other threads don’t read or modify, no consistency problems will exist.
Similarly, if a variable is read-only, there is no consistency problem with more
than one thread reading its value at the same time. However, when one thread
can modify a variable that other threads can read or modify, we need to
synchronize the threads to ensure that they don’t use an invalid value when
accessing the variable’s memory contents. A mutex is basically a lock that we set
(lock) before accessing a shared resource and release (unlock) when we’re done.
While it is set, any other thread that tries to set it will block until we release it. If
more than one thread is blocked when we unlock the mutex, then all threads
blocked on the lock will be made runnable, and the first one to run will be able
to set the lock. Dining philosopher is a problem based on thread synchronization.
Dining Philosophers Problem
There are some Philosophers whose work is just thinking and eating. Let there
are 5 (for example) philosophers. They sat at a round table for dinner. To
complete dinner each must need two Forks (spoons). But there are only 5 Forks
available (Forks always equal to no. of Philosophers) on table. They take in such
a manner that, first take left Fork and next right Fork. But problem is they try to
take at same time. Since they are trying at same time, Fork 1, 2, 3, 4, 5 taken by
Philosopher 1, 2, 3, 4, 5 respectively (since they are left side of each). And each
one tries to ta ke right side Fork. But no one found available Fork. And also that
each one thinks that someone will release the Fork and then I can eat. This
continuous waiting leads to Dead Lock situation.

Solution: To solve this Dead Lock situation, Last philosopher (any one can do
this) first try to take right side fork and then left side fork. i.e in our example 5th
person tries to take 4th Fork instead of 5th one. Since 4th Fork already taken by
4th the person, he gets nothing. But he left 5th Fork. Now the first person will
take this 5th Fork and complete dinner and make 1st and 5th available for
remaining people. Next 2nd person takes 1st fork and completes and releases 1st
and 2nd. This continuous until all finishes dinner.
Output:
Philosopher 1 is thinking
Philosopher 2 is thinking
Philosopher 3 is thinking
Philosopher 4 is thinking
Philosopher 5 is thinking
Philosopher 5 is Hungry
Philosopher 5 takes fork 4 and 5

38
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Philosopher 5 is Eating
Philosopher 3 is Hungry
Philosopher 3 takes fork 2 and 3
Philosopher 3 is Eating
Philosopher 1 is Hungry
Philosopher 4 is Hungry
Philosopher 2 is Hungry
Philosopher 5 putting fork 4 and 5 down
Philosopher 5 is thinking
Philosopher 1 takes fork 5 and 1
Philosopher 1 is Eating
Philosopher 3 putting fork 2 and 3 down
Philosopher 3 is thinking
Philosopher 4 takes fork 3 and 4
Philosopher 4 is Eating
Philosopher 5 is Hungry
Result:
Thus a C program to implement threading and synchronization
applications was successfully executed and the output was verified.

VIVA QUESTIONS
1. What is a thread?
2. What is process synchronization?
3. What is producer consumer problem?
4. What is multithreading?
5. Why synchronization is needed?
6. Thread synchronization is required because
a) all threads of a process share the same address space
b) all threads of a process share the same global variables
c) all threads of a process can share the same files
7.  A deadlock free solution to the dining philosophers problem :
a) necessarily eliminates the possibility of starvation
b) does not necessarily eliminate the possibility of starvation
c) eliminates any possibility of any kind of problem further
8. The bounded buffer problem is also known as :
a) Readers – Writers problem b) Dining – Philosophers problem
c) Producer – Consumer problem
9. What is a thread pool?
10. The number of the threads in the pool can be decided on factors such as :
a) number of CPUs in the system b) amount of physical memory
c) expected number of concurrent client requests

39
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex.No.11 IMPLEMENTATION OF MEMORY MANAGEMENT


TECHNIQUES
FIRST FIT, BEST FIT AND WORST FIT

Aim:
To write a c program to implement memory management techniques such as first fit,
best fit and worst fit.

Description:
MEMORY MANAGEMENT
The purpose of the memory manager is
 to allocate primary memory space to processes
 to map the process address space into the allocated portion of the primary
memory
 to minimize access times using a cost-effective amount of primary memory

Memory Management Algorithms


In an environment that supports dynamic memory allocation, the memory manager
must keep a record of the usage of each allocatable block of memory. This record
could be kept by using almost any data structure that implements linked lists. An
obvious implementation is to define a free list of block descriptors, with each
descriptor containing a pointer to the next descriptor, a pointer to the block, and the
length of the block. The memory manager keeps a free list pointer and inserts entries
into the list in some order conducive to its allocation strategy. A number of strategies
are used to allocate space to the processes that are competing for memory.
Best Fit
The allocator places a process in the smallest block of unallocated memory in which it
will fit.
Problems:
 It requires an expensive search of the entire free list to find the best hole.
 More importantly, it leads to the creation of lots of little holes that are not big
enough to satisfy any requests. This situation is called fragmentation, and is a problem
for all memory-management strategies, although it is particularly bad for best-fit.

Solution:One way to avoid making little holes is to give the client a bigger block than
it asked for. For example, we might round all requests up to the next larger multiple of
64 bytes. That doesn't make the fragmentation go away, it just hides it.
 Unusable space in the form of holes is called external fragmentation
Worst Fit
The memory manager places process in the largest block of unallocated memory
available. The ides is that this placement will create the largest hole after the
allocations, thus increasing the possibility that, compared to best fit, another process
can use the hole created as a result of external fragmentation.
First Fit
Another strategy is first fit, which simply scans the free list until a large enough hole is
found. Despite the name, first-fit is generally better than best-fit because it leads to less
fragmentation.
Algorithm
1.Start the program.
2.Enter the number and size of blocks, number of files.

40
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

3.In first fit, allocate the process to free memory by sequential order if free memory
size>=process size.
4.In best fit, allocate the process to free memory, if the memory size is first, equal to
free memory then go for greater memory size.
5.In worst fit, allocate the process to free memory, if the memory size is greater then
go for equal memory size.
6.Stop the program.

INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:- File 1: 1
File 2: 4
OUTPUT
File No File Size Block No Block Size Fragment
1 1 1 5 4
2 4 3 7 3

BEST-FIT
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4
OUTPUT
File No File Size Block No Block Size Fragment
1 1 2 2 1
2 4 1 5 1
FIRST-FIT
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4
OUTPUT
File No File Size Block No Block Size Fragment

41
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

1 1 3 7 6
2 4 1 5 1
Result:
Thus the program for memory management technique first fit, best fit and worst fit
has been implemented successfully and the output was verifed.

42
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex. No: 12 IMPLEMENT PAGING TECHNIUE OF MEMORY


MANAGEMENT

Aim:
Write a C program to implement paging technique of Memory
management.
Description:
Memory management is the functionality of an operating system which handles
or manages primary memory and moves processes back and forth between main
memory and disk during execution. Memory management keeps track of each
and every memory location, regardless of either it is allocated to some process or
it is free. It checks how much memory is to be allocated to processes. It decides
which process will get memory at what time. It tracks whenever some memory
gets freed or unallocated and correspondingly it updates the status. The set of all
logical addresses generated by a program is referred to as a logical address
space. The set of all physical addresses corresponding to these logical addresses
is referred to as a physical address space.
Paging
A computer can address more memory than the amount physically installed on
the system. This extra memory is actually called virtual memory and it is a
section of a hard that's set up to emulate the computer's RAM. Paging technique
plays an important role in implementing virtual memory.
Paging is a memory management technique in which process address space is
broken into blocks of the same size called pages (size is power of 2, between
512 bytes and 8192 bytes). The size of the process is measured in the number of
pages.
Similarly, main memory is divided into small fixed-sized blocks of (physical)
memory called frames and the size of a frame is kept the same as that of a page
to have optimum utilization of the main memory and to avoid external
fragmentation.

43
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Address Translation
Page address is called logical address and represented by page number and
the offset.
Logical Address = Page number + page offset

Frame address is called physical address and represented by a frame


number and the offset.

Physical Address = (Frame number * Frame size) + page offset

A data structure called page map table is used to keep track of the relation
between a page of a process to a frame in physical memory.

Algorithm:
1.Start the program.
2.Read physical memory, logical memory and partition size.
3.Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
4.Display the page table, frame table and physical address.
5.Stop the program.

OUTPUT:
MEMORY MANAGEMENT USING PAGING
Enter the Size of Physical memory: 16
Enter the size of Logical memory: 8
Enter the partition size: 2
The physical memory is divided into 8 no.of frames
The Logical memory is divided into 4 no.of pages
Enter the Frame number where page 0 must be placed: 5
Enter the Frame number where page 1 must be placed: 6
Enter the Frame number where page 2 must be placed: 7
Enter the Frame number where page 3 must be placed: 2

44
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

PAGE TABLE
PageAddress FrameNo. PresenceBit

0 5 1
1 6 1
2 7 1
3 2 1

FRAME TABLE
FrameAddress PageNo

0 32555
1 32555
2 3
3 32555
4 32555
5 0
6 1
7 2
Process to create the Physical Address
Enter the Base Address: 1000
Enter theLogical Address: 3

The Physical Address where the instruction present: 1013

Result:
Thus a C program to implement paging technique of Memory management
was implemented and the output was verified successfully.

VIVA QUESTIONS
1. What is paging?
2. What is page table?
3. What is physical address?
4. What is logical address?
5. What is virtual memory?
6. What are frames?
7. How physical address is calculated?
8. What is an offset?
9. What is mapping?
10. What is page number and frame number?

45
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex. No: 13 IMPLEMENT ALL PAGE REPLACEMENT


ALGORITHM

Aim:
Write the C program to implement all page replacement algorithms
a) First In First Out(FIFO)
b) Least Recently Used(LRU)
c)Least Frequently Used(LFU)
Description:
Page Replacement Algorithm
Page replacement algorithms are the techniques using which an Operating
System decides which memory pages to swap out, write to disk when a page of
memory needs to be allocated. Paging happens whenever a page fault occurs
and a free page cannot be used for allocation purpose accounting to reason that
pages are not available or the number of free pages is lower than required
pages. There are many different page replacement algorithms such as
 First In First Out(FIFO)
 Least Recently Used(LRU)
 Least Frequently Used(LFU)
First In First Out (FIFO) algorithm
 Oldest page in main memory is the one which will be selected for
replacement.
 Easy to implement, keep a list, replace pages from the tail and add new
pages at the head.

Least Recently Used (LRU) algorithm


 Page which has not been used for the longest time in main memory is the
one which will be selected for replacement.
 Easy to implement, keep a list, replace pages by looking back into time.

46
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Least frequently Used (LFU) algorithm


 The page with the smallest count is the one which will be selected for
replacement.
 The simplest method to employ an LFU algorithm is to assign a counter
to every block that is loaded into the cache. Each time a reference is
made to that block the counter is increased by one. When the cache
reaches capacity and has a new block waiting to be inserted the system
will search for the block with the lowest counter and remove it from the
cache
 This algorithm suffers from the situation in which a page is used heavily
during the initial phase of a process, but then is never used again.
Optimal Page replacement algorithm
 An optimal page-replacement algorithm has the lowest page-fault rate of
all algorithms. An optimal page-replacement algorithm exists, and has
been called OPT or MIN.
 Replace the page that will not be used for the longest period of time. Use
the time when a page is to be used.

Ex.No: 13.a) FIFO PAGE REPLACEMENT ALGORITHM


Aim:
Write a C program to implement First In First Out (FIFO) page
replacement algorithm.

Algorithm:
1.Start the program.

47
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

2.Create a queue to hold all pages in memory.


3.When the page is required replace the page at the head of the queue.
4.The new page is inserted at the tail of the queue and the number of page fault
is displayed.
5.Stop the program.

Output:
Enter no.of frames....4
Enter number of reference string..
6

Enter the reference string..


564123

The given reference string:


...................................... 5 6 4 1 2 3

Reference np5-> 5 -1 -1 -1
Reference np6-> 5 6 -1 -1
Reference np4-> 5 6 4 -1
Reference np1-> 5 6 4 1
Reference np2-> 2 6 4 1
Reference np3-> 2 3 4 1

No.of pages faults...6

Result:
Thus the C program to implement First In First Out (FIFO) page
replacement algorithm was successfully executed and the result is verified.

Ex. No: 13(b) LRU PAGE REPLACEMENT ALGORITHM

Aim:
Write a C program to implement Least Recently Used (LRU) page
replacement algorithm .

ALGORITHM:
1.Start the program.
2.Read the number of frames.
3. Read the number of reference string.
4. Read the reference string.
5. Initialize the values in frames to -1.
6. Allocate the pages in to frames by selecting the page that has not been used
for the longest period of time.
7. Display the number of page faults.
8.Stop the program.
Output
LRU PAGE REPLACEMENT ALGORITHM

Enter no.of Frames....3

48
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Enter no.of reference string..6

Enter reference string..


654231

LRU PAGE REPLACEMENT ALGORITHM


The given reference string:
…………………. 6 5 4 2 3 1

Reference NO 6-> 6 -1 -1
Reference NO 5-> 6 5 -1
Reference NO 4-> 6 5 4
Reference NO 2-> 2 5 4
Reference NO 3-> 2 3 4
Reference NO 1-> 2 3 1

No.of page faults...6


Result:
Thus the C program to implement Least Recently Used(LRU) page
replacement algorithm was successfully executed and the result is verified.

Ex. No: 13(c) LEAST FREQUENTLY USED ALGORITHM

Aim:
Write a C program to implement Least Frequently Used (LFU) page
replacement algorithms
Algorithm:
1.Start the program.
2.Read the number of frames.
3. Read the number of reference string.
4. Read the reference string.
5. Initialize the values in frames to -1.
6. Allocate the pages in to frames by selecting the page with the smallest count
is the one which will be selected for replacement.
7. Display the number of page faults.
8. Stop the program.

OUTPUT:

OPTIMAL PAGE REPLACEMENT ALGORITHM

Enter no.of Frames....3


Enter no.of reference string..6

Enter reference string..


654231

OPTIMAL PAGE REPLACEMENT ALGORITHM


The given reference string:

49
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

…………………. 6 5 4 2 3 1

Reference NO 6-> 6 -1 -1
Reference NO 5-> 6 5 -1
Reference NO 4-> 6 5 4
Reference NO 2-> 2 5 4
Reference NO 3-> 2 3 4
Reference NO 1-> 2 3 1

No.of page faults...6


Result:
Thus the C program to implement Least Frequently Used(LFU) page
replacement algorithm was successfully executed and the result is verified.
VIVA QUESTIONS
1. A process refers to 5 pages, A, B, C, D, E in the order : A, B, C, D, A, B,
E, A, B, C, D, E. If the page replacement algorithm is FIFO, the number of
page transfers with an empty internal store of 3 frames is :
a) 8 b) 10 c) 9 d) 7
2. A memory page containing a heavily used variable that was initialized
very early and is in constant use is removed, then the page replacement
algorithm used is :
a) LRU b) LFU c) FIFO d) None of the mentioned
3. Users _______ that their processes are running on a paged system.
a) are aware b) are unaware c) may unaware d) none of the mentioned
4.  If no frames are free, _____ page transfer(s) is/are required.
a) one b) two c) three d) four
5. When a page is selected for replacement, and its modify bit is set :
a) the page is clean
b) the page has been modified since it was read in from the disk
c) the page is dirty
d) the page has been modified since it was read in from the disk & page is
dirty
6. The aim of creating page replacement algorithms is to :
a) replace pages faster b) increase the page fault rate
c) decrease the page fault rate d) to allocate multiple pages to processes
7. A FIFO replacement algorithm associates with each page the _______
a) time it was brought into memory b) size of the page in memory
c) page after and before it d) all of the mentioned
8. LRU page – replacement algorithm associates with each page the ______
a) time it was brought into memory b) the time of that page’s last use
c) page after and before it d) all of the mentioned
9. When using counters to implement LRU, we replace the page with the :
a) smallest time value b) largest time value
c) greatest size d) none of the mentioned
10. he reason for using the LFU page replacement algorithm is :
a) an actively used page should have a large reference count
b) a less used page has more chances to be used again
c) it is extremely efficient and optimal
d) all of the mentioned.

50
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex.No: 14 IMPLEMENT ALL FILE ALLOCATION STRATEGIES


Aim:
Write a C program to implement file allocation strategies such as
a) Sequential file allocation
b) Indexed file allocation
c) Linked file allocation
Description:
A file is a named collection of related information that is recorded on secondary
storage such as magnetic disks, magnetic tapes and optical disks. 
File Allocation
Files are allocated disk spaces by operating system. Operating systems deploy
following three main ways to allocate disk space to files.
 Sequential Allocation
 Linked Allocation
 Indexed Allocation
Sequential Allocation
 Each file occupies a contiguous address space on disk.
 Assigned disk address is in linear order.
 Easy to implement.
 External fragmentation is a major issue with this type of allocation
technique.

Linked Allocation
 Each file carries a list of links to disk blocks.
 Directory contains link / pointer to first block of a file.
 No external fragmentation
 Effectively used in sequential access file.
 Inefficient in case of direct access file.

Indexed Allocation
 Provides solutions to problems of contiguous and linked allocation.
 A index block is created having all pointers to files.
 Each file has its own index block which stores the addresses of disk
space occupied by the file.
 Directory contains the addresses of index blocks of files.

51
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex. No: 14(a) SEQUENTIAL FILE ALLOCATION

AIM:
Write a C Program to implement Sequential File Allocation method.

ALGORITHM:
1. Start the program.
2. Read the number of files.
3. For each file, read the number of blocks required and the starting block of the
file.
4. Allocate the blocks sequentially to the file from the starting block.
5. Display the file name, starting block , and the blocks occupied by the file.
6.Stop the program.

OUTPUT:
Enter no.of files: 2
Enter no. of blocks occupied by file1 4
Enter the starting block of file1 2
Enter no. of blocks occupied by file2 10
Enter the starting block of file2 5
Filename Start block length
1 2 4
2 5 10

Result:
Thus the C Program to implement Sequential File Allocation method was
executed successfully and the result is verified.

Ex.No: 14(b) INDEXED FILE ALLOCATION

Aim:
Write a C Program to implement Indexed File Allocation method.

Algorithm:
1. Start the program.
2. Read the number of files
3. Read the index block for each file.
4. For each file, read the number of blocks occupied and number of blocks of the
file.
5. Link all the blocks of the file to the index block.
6. Display the file name, index block, and the blocks occupied by the file.

52
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

7. Stop the program.

OUTPUT:
Enter no. of files: 2
Enter index block 3
Enter blocks occupied by file1: 4
Enter blocks of file1:
9467
Enter index block 5
Enter blocks occupied by file2: 2
enter blocks of file2: 10 8
File Index Length
1 3 4
2 5 2
Blocks occupied are:
file1 3--->9 3--->4 3--->6 3--->7
file2 5--->10 5--->8
Result:
Thus the C Program to implement indexed File Allocation method was
executed successfully and the result is verified.

Ex.No: 14(c) LINKED FILE ALLOCATION

Aim:
Write a C Program to implement Linked File Allocation method.

Algorithm:
1. Start the program.
2. Read the number of files.
3. For each file, read the file name, starting block, number of blocks and block
numbers of the file.
4. Start from the starting block and link each block of the file to the next block in
a linked list fashion.
5. Display the file name, starting block, size of the file , and the blocks occupied
by the file.
6. Stop the program.

Output:
Enter no. of files : 2
Enter file name : venkat
Enter starting block : 20
Enter no.of blocks : 6
Enter block numbers : 4
12
15
45
32
25
Enter file name : rajesh
Enter starting block : 12

53
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Enter no.of blocks : 5


Enter block numbers : 6
5
4
3
2
File start size block
venkat 20 6 4--->12--->15--->45--->32--->25
rajesh 12 5 6--->5--->4--->3--->2

Result:
Thus the C Program to implement linked File Allocation method was
executed successfully and the result is verified.

VIVA QUESTIONS:
1.What file access pattern is particularly suited to chained file allocation on
disk?
2. Define Sequential File allocation
3. Why we use file allocation strategies?
4.what are the advantages and dis-advantages of Sequential File allocation?
5. The average waiting time =________________________________.
6. What file allocation strategy is most appropriate for random access files?
7.Define File?
8.Define Directory?
9. Why we use file allocation strategies?
10.what are the advantages and dis-advantages Indexed Allocation?
11.What file access pattern is particularly suited to chained file allocation on
disk?
12. What file allocation strategy is most appropriate for random access files?
13.Mention different file allocation strategies?
14. Why we use file allocation strategies?
15.what are the advantages and dis-advantages of each strategies?
16. The ______________contains a pointer to the first and last blocks of the file.

54
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

Ex.No. 15 IMPLEMENT ALL FILE ORGANIZATION TECHNIQUE


Aim:
Write a C program to implement file organization technique such as
a) Single level directory
b) Two level directory
c) Hierarchical level Directory
d) Direct Acyclic Graph(DAG)
Description:
File organization refers to the way data is stored in a file. File organization is
very important because it determines the methods of access, efficiency,
flexibility and storage devices to use. A directory that contains all the files is the
simplest form of the directory system and is also called as root directory. There
are four methods of organizing files on a storage media. This includes:
 Single level directory
 Two level directory
 Hierarchical level Directory
 Direct Acyclic Graph(DAG)
Single level directory
In this type of directory system, there is a root directory which has all files. It has
a simple architecture and there are no sub directories. Advantage of single level
directory system is that it is easy to find a file in the directory.

Two level directory


Each user gets their own directory space. File names only need to be unique
within a given user's directory. A master file directory is used to keep track of
each users directory, and must be maintained when users are added to or
removed from the system. A separate directory is generally needed for system
( executable ) files. Systems may or may not allow users to access other
directories besides their own

Hierarchical level Directory


In a hierarchical directory system, files are grouped together to form a sub
directory  At the top of the hierarchy is the root directory and then there are sub
directories which has files. Advantage of hierarchical directory system is that
users can be provided access to a sub directory rather than the entire directory. It
provides a better structure to file system. Also, managing millions of files is easy

55
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

with this architecture. Personal computers use hierarchical directory system for
managing files.

Direct Acyclic Graph(DAG)


Allow directories to link to one another, allow multiple directories to
contain same file i.e., only one copy of the file exists and any change in the
file can be viewed by all directories in which it is contained. Results in
Acyclic graphs. Two users can name same file or same directory. Duplicate
paths may complicate task of backing up periodically.

Ex.No: 15.a) SINGLE- LEVEL DIRECTORY

Aim:
Write a C program to implement Single level Directory in file organization.
Algorithm:
1. Start the program.
2.Intialize struct with filename, directory name.
3.Read the directory name and option for switch case.
4. If the operation to be performed is to create file , a new file under the root directory
is created.
5. The file created under the root directory can be searched deleted.
6.stop the program.

56
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

OUTPUT:
Enter name of directory -- IT

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

Result:
Thus the program to implement Single level directory was executed and
verified successfully

Ex.No. 15(b) TWO LEVEL DIRECTORY

Aim:
Write a C program to implement Two level Directory in file organization.
Algorithm:
1. Start the program.
2. Initialize values dname[10],fname[10][10],dir[10],dcnt;
3. Read number of directories.

57
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

4. Read file name under each directory.


5. If the directory name matches with the existing directory create and display the files
under the mentioned directory name.
6. Include the created directories under a single root directory.
7. If a filename which does not exist under a directory is mentioned, then print file not
found.
8. Stop the program.

OUTPUT:
1. Create Directory 2. Create File 3. Delete File
4. Search File 5. Display 6. Exit Enter your choice -- 1

Enter name of directory -- DIR1


Directory created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 1

Enter name of directory -- DIR2

Directory created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 2

Enter name of the directory – DIR1


Enter name of the file -- A1
File created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 2

Enter name of the directory – DIR1


Enter name of the file -- A2
File created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 2

Enter name of the directory – DIR2


Enter name of the file -- B1
File created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 5
Directory Files
DIR1 A1 A2
DIR2 B1

58
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 4

Enter name of the directory – DIR


Directory not found

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 3
Enter name of the directory – DIR1
Enter name of the file -- A2

File A2 is deleted

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice – 6

Result:
Thus the program to implement Two level directory was executed and verified
successfully

Ex. No. 15(c) HIERARCHICAL DIRECTORY

Aim:
Write a C program to implement Hierarchical level Directory in file
organization.

Algorithm:
1.Start the program.
2. Initialize values x,y,ftype,lx,rx,nc,level.
3. Initialize struct tree_element to store pointers.
4.Read number of directories under root directory.
5. Read file name under each directory.
6. All sub directories holds two pointers. One is to point its child directory/filename
and another is to points its parent directory.
7. If the directory name matches with the existing directory create and display the files
under the mentioned directory name.
8. Include the created directories under a single root directory.
9. If a filename which does not exist under a directory is mentioned, then print file not
found.
10. Stop the program.

OUTPUT:
Enter Name of dir/file (under root): ROOT
Enter 1 for Dir / 2 For File : 1
No of subdirectories / files (for ROOT) :2
Enter Name of dir/file (under ROOT):USER 1
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for USER 1):1
Enter Name of dir/file (under USER 1):SUBDIR
Enter 1 for Dir /2 for file:1

59
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

No of subdirectories /files (for SUBDIR):2


Enter Name of dir/file (under USER 1):
JAVA Enter 1 for Dir /2 for file:1
No of subdirectories /files (for JAVA): 0
Enter Name of dir/file (under SUBDIR):VB
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for VB): 0

Enter Name of dir/file (under ROOT):USER2


Enter 1 for Dir /2 for file:1
No of subdirectories /files (for USER2):2
Enter Name of dir/file (under ROOT):A
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under USER2):SUBDIR 2
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for SUBDIR 2):2

Enter Name of dir/file (under SUBDIR2):PPL


Enter 1 for Dir /2 for file:1
No of subdirectories /files (for PPL):2
Enter Name of dir/file (under PPL):B
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under PPL):C
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under SUBDIR):AI
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for AI): 2
Enter Name of dir/file (under AI):D
Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under AI):E

Result:
Thus the program to implement Hierarchical directory was executed and
verified successfully.

Ex. No. 15(d) DIRECT ACYCLIC GRAPH (DAG)

Aim:
Write a C program to implement Direct Acyclic Graph (DAG ) in File
Organization Technique .
Algorithm:

60
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

1.Start the program


2.Collect set of nodes 1, 2, ..., n
3.Get the value of an edge (i,j) whenever i < j
4.Calculate N-choose-2 = n(n-1)/2 edges, but no cycles.
5.Stop the program.

Output:

Result:
Thus the program to implement Direct Acyclic Graph was executed and
verified successfully.

VIVA QUESTIONS
1. What is file organization?
2. What are advantages and disadvantages in single level directory?
3. What are advantages and disadvantages in two level directory?
4. What are advantages and disadvantages in hierarchical level directory?
5. What is root directory?
6. What is DAG?
7. List some of the file organization technique?
8. What is the advantages of organizing the files?
9. List out the file accessing permissions.
10. What is a sub directory?

61
KLNCE/IT /2018-2019 (EVEN) CS8461-OPERATING SYSTEMS LAB

CONTENT BEYOND SYLLABUS


MEMORY MANAGEMENT SCHEME-SEGMENTATION
AIM:
To write a C program to implement memory management using segmentation
ALGORITHM:
Step1 : Start the program.
Step2 : Read the base address, number of segments, size of each segment, memory
limit.
Step3 : If memory address is less than the base address display “invalid memory
limit”.
Step4 : Create the segment table with the segment number and segment address and
display it.
Step5 : Read the segment number and displacement.
Step6 : If the segment number and displacement is valid compute the real address and
display the same.
Step7 : Stop the program.
Sample Input 1:
Program for segmentation
Enter the number of segments:3
Enter the base address and limit register:
100 50
150 20
130 34
Enter the Logical address:25
Sample Output 1:
PageNo.BaseAdd.PhysicalAdd.
2 130 155
Sample Input 2:
Program for segmentation
Enter the number of segments:2
Enter the Logical address and limit register:
100 50
150 20
Enter the logical address:25
Sample Output 2:
page size exceeds
RESULT:
Thus the program for implementing the segmentation concept was executed and the
output was verified successfully.

62

You might also like