OS Lab Manual
Topics covered
OS Lab Manual
Topics covered
TIRUNELVELI
LAB MANUAL
CS8461 OPERATING SYSTEMS
LABORATORY
i
Course Syllabus
IT6412 OPERATING SYSTEMS LABORATORY LTPC0042
OBJECTIVES
To learn Unix commands and shell programming
To implement various CPU Scheduling Algorithms
To implement Process Creation and Inter Process Communication.
To implement Deadlock Avoidance and Deadlock Detection Algorithms
To implement Page Replacement Algorithms
To implement File Organization and File Allocation Strategies
LIST OF EXPERIMENTS
OUTCOMES:
At the end of the course, the student should be able to
Compare the performance of various CPU Scheduling Algorithms
Implement Deadlock avoidance and Detection Algorithms
Implement Semaphores
Create processes and implement IPC
ii
Analyze the performance of the various Page Replacement Algorithms
Implement File Organization and File Allocation Strategies
Course Objectives
Course Outcomes
Mapping of PO with CO
iii
Implement Deadlock avoidance
processes
implement IPC
Program
Algorithms
Algorithms
Outcomes
Create
POa Engineering Knowledge: Apply
knowledge of mathematics, science,
L L
engineering fundamentals and an engineering M L H
specialization for building engineering
models.
iv
Implement Deadlock avoidance
processes
implement IPC
Program
Algorithms
Algorithms
Outcomes
Create
POh Ethics: Apply ethical principles and
commit to professional ethics,
responsibilities and norms of engineering
practice.
v
[Link] No of
Name of the Exercise
Hours
1 LIST OF EXPERIMENTS
Basics of UNIX commands 6
3 Write C programs to simulate UNIX commands like cp, ls, grep, etc 3
4 Shell Programming 3
6 Implementation of Semaphores 3
Total Hours: 60
vi
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Objective:
To learn about Basic Unix commands
Aim:
To execute the basic UNIX commands
Introduction:
The UNIX operating system has for many years formed the backbone of the Internet,
especially for large servers and most major university campuses. However, a free version of
UNIX called Linux has been making significant gains against Macintosh and the Microsoft
Windows 95/98/NT environments, so often associated with personal computers.
Developed by a number of volunteers on the Internet such as the Linux group and the GNU
project, much of the open-source software is copyrighted, but available for free. This is
especially valuable for those in educational environments where budgets are often limited.
UNIX commands can often be grouped together to make even more powerful commands
with capabilities known as I/O redirection ( < for getting input from a file input and > for
outputing to a file ) and piping using | to feed the output of one command as input to the
next. Please investigate manuals in the lab for more examples than the few offered here.
Definition:
Unix (often spelled "UNIX," especially as an official trademark) is an operating
system that originated at Bell Labs in 1969 as an interactive time-sharing system. Ken
Thompson and Dennis Ritchie are considered the inventors of Unix. The name (pronounced
YEW-nihks) was a pun based on an earlier system, Multics. In 1974, Unix became the first
operating system written in the C language. Unix has evolved as a kind of large freeware
product, with many extensions and new ideas provided in a variety of versions of Unix by
different companies, universities, and individuals.
Theory:
Ten ESSENTIAL UNIX Commands
These are ten commands that you really need to know in order to get started with UNIX. They are
probably similar to commands you already know for another operating system.
1
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
2
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
3
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
4
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
10. mpage <opt> mpage -8 file1 | Print 8 pages on a single sheet and
<file> lpr send to printer (the font will be
small!)
5
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
3. alias alias lls="ls -alF" Create new command "lls" for long
format of ls
6
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Software Required:
telenet
Procedure:
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start learning with typing basic UNIX commands.
1. Creating a file:
Syntax: $ cat> filename
The cat command reads the standard input (the keyboard) and the > redirects the
Output, which normally goes to the screen, into a file
Output
[cse01@telnet ~]$ cat > display_file
cse01
Good Girl
Study well
7
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Eat well
Sleep well
Output
[cse01@telnet ~]$ cat display_file
cse01
Good Girl
Study well
Eat well
Sleep well
Output
[cse01@telnet ~]$ cat >> display_file
Thus cse01 can be crowned the best
8
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output
Output
[cse01@telnet ~]$ cp concatenated_file copied_file
[ cse01@telnet ~]$ cat copied_file
cse01
Good Girl
Study well
Eat well
Sleep well
Thus cse01 can be crowned the best
This a new file created to demonstrate concatenation of files
9
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
To move a file from one place to another, the mv command is used. This has the
effect of moving rather than copying the file. It can also be used to rename a file, by moving
the file to the same directory, but giving it a different name. The source won’t exist after
renaming or moving.
e.g., $ mv myfile1 myfile2
Output
Output
Output
[cse01@telnet ~]$ mkdir exjayan
10
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output
[cse01@telnet exjayan]$ cd
[cse01@telnet ~]$ rmdir exjayan
[cse01@telnet ~]$ cd exjayan
-bash: cd: exjayan: No such file or directory
Output
Output
[cse01@telnet ~]$ cd ex
[cse011@telnet ex]$
Output
11
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
[cse01@telnet ~]$ cd ex
[cse01@telnet ex]$
Output
[cse01@telnet ex]$ cd
[cse01telnet ~]$
12
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output
[cse01@telnet ~]$ ls -a
. matrix
.. newcountries
alpha_numbers new_file
[Link] newsortcountries
Arithmetic_Manipulation nish
Arithmetic_Operations nisha
.bash_history numbers
.bash_logout Output_File
.bash_profile Palindrome1.c
.bashrc Palindrome.c
Biggest_Two Palindrome_Checking.c
.canna .Palindrome_Checking.[Link]
concatenated_file Read_File
Count_Characters.c Reverse_file.c
Count_Characters_File.c Reverse_File.c
countries salary
countries_sort Salary
Display_20Lines.c Sort
display_file sortcountries
Display_File_Contents.c String_Comparison
.Display_File_Contents.swo Student
.Display_File_Contents.swp Student1
.emacs Sum_Even_Numbers
greetings Sum_N_Natural_Numbers
.gtkrc Transpose_Matrix.c
hello unix_file
ignisha .viminfo
Input_File .[Link]
.kde ex
Largest_Three .xemacs
lynx_bookmarks.html .zshrc
13
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
E.g., $ls -t
Output
[cse01@telnet ~]$ ls -t
ex Count_Characters_File.c nisha
concatenated_file Display_File_Contents.c alpha_numbers
new_file Input_File numbers
display_file Reverse_File.c countries_sort
Arithmetic_Operations Display_20Lines.c newsortcountries
Output_File Sum_N_Natural_Numbers sortcountries
Reverse_file.c Biggest_Two newcountries
matrix greetings countries
[Link] Sum_Even_Numbers lynx_bookmarks.html
Transpose_Matrix.c Arithmetic_Manipulation Student1
Palindrome_Checking.c String_Comparison Student
Palindrome.c Largest_Three salary
Palindrome1.c hello Sort
Count_Characters.c nish Salary
Read_File ignisha unix_file
Output
[cse01@telnet ~]$ wc new_file
1 10 62 new_file
Output
[cse01@telnet ~]$ wc -l new_file
1 new_file
14
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output
[cse01@telnet ~]$ wc -c new_file
62 new_file
Output
[cse01@telnet ~]$ file new_file
new_file: ASCII text
Output
[cse01@telnet ~]$ ls > new_file
[cse01@telnet ~]$ cat new_file
alpha_numbers
[Link]
Arithmetic_Manipulation
Arithmetic_Operations
Biggest_Two
concatenated_file
greetings
hello
15
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
ignisha
Input_File
Largest_Three
lynx_bookmarks.html
matrix
newcountries
new_file
newsortcountries
nish
nisha
ex
23. PATH:
Syntax: $echo $PATH
It’s used to display the current path of the operating system
E.g., $echo $PATH
Output
Output
Aim:
To execute the general purpose commands in UNIX.
16
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
The date command is used to display the current date with day of week, month,day,
time (24 hours clock) and the year.
Syntax
$ date
E.g.,
$ date
Thu Jan 29 [Link] IST 2009
The date command can also be used with following format specifications. The
format specifications must be preceded by a (+) symbol followed by (%) operator and a
single character.
E.g.,
$ echo learning unix is fun
learning unix is fun
Echo command-Output
17
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
[Link] Command
The cal (calendar) command is used to display the month or year.
Syntax
$ cal month or year
E.g.,
$ cal 2009 - Prints the calendar for the entire year
$ cal 9 2009 – Prints the calendar for the month of September 2009
Cal Command-Output
[cse01@telnet ~]$ cal
January 2009
Su Mo Tu We Th Fr Sa
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
2009
18
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
18 19 20 21 22 23 24 22 23 24 25 26 27 28 22 23 24 25 26 27 28
25 26 27 28 29 30 31 29 30 31
4. bc command
The bc command is used for carrying out arithmetic manipulations. It is the online
calculator, which can be invoked for carrying out complex functions.
Syntax
$ bc
E.g.,
$ bc
It does not display the command prompt and simply waits for the user to type in values. bc
continuous this process unitl the user enters CTRL + D to terminate.
bc command-Output
[cse01@telnet ~]$ bc
bc 1.06
19
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
5+5
10
15 - 5
10
15 / 5
3
12 * 3
36
[Link] command
The who command is used to know the users who are currently logged into the
sytem.
Syntax
$ who
E.g.,
$ who
who command-Output
[Link] am i Command
The who command with am and i display a single line of Output pertaining to the
login details of the user.
Syntax
$ who am i
E.g.,
$ who am I
20
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
The who am i command identifies the user and lists the user name, terminal line,
the date and time of login.
The who command has several command-line options as given below
who am i - Output
[Link] command
The finger command gathers and displays the information about the users, which
includes login name, the name of the user , the home directory etc.
Syntax
$ finger username
E.g.,
$ finger vijayan
To display the information about all users who are logged in, enter as given below
$ finger
E.g.,
$ finger
Login Name Tty Idle Login Time Office Of
cse01 pts/17 Jan 30 15:30 ([Link])
21
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
No mail.
No Plan.
8. id command
The id command is used to display the numerical value that corresponds to the user
login name i.e., every valid UNIX user is assigned a login name, a user and a group-id.
Syntax
$ id
E.g.,
$ id
uid=502(mtec11) gid=512(mtec11) groups=512(mtec11)
context=user_u:system_r:un confined_t
id command – Output
[cse01@telnet ~]$ id
uid=502(mtec11) gid=512(mtec11) groups=512(mtec11) context=user_u:system_r:un
confined_t
9. tty command
The tty (teletype) command is used to know the terminal name that the user is
using.
Syntax
$ tty
E.g.,
$ tty
/dev/pts/10
tty command-Output
[cse01@telnet ~]$ tty
/dev/pts/10
Result
Thus the General Purpose commands were executed the Output was verified.
COMMAND GROUPING
Aim:
To execute the grouping commands in UNIX
[Link] (;)
22
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Unix has a limitation to execute only one command at a time, the semicolon
operator(;) overcomes this limitation and can be used to separate multiple commands at
the command line.
Syntax
$ command1; command2;…commandn
where command1; command2;…commandn are the UNIX commands separated by
semicolon operator.
E.g.,
$ who;date
murugan pts/10 Jan 29 14:25 ([Link])
muthu pts/4 Jan 29 14:27 ([Link])
Thu Jan 29 [Link] IST 2009
It executes both the commands at a time
Semicolon (;)-Output
2.&& operator
The && operator signifies the logical AND operation. In this case, only if the first
command is successfully executed then the next command will be executed.
Syntax
$ command1 && command2 && ……..commandn
E.g.,
$ who && date
murugan pts/10 Jan 29 14:25 ([Link])
23
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
&& operator-Output
[cse01@telnet ~]$ who && date
cse01 pts/10 Jan 29 14:25 ([Link])
monica pts/4 Jan 29 14:27 ([Link])
Thu Jan 29 [Link] IST 2009
3.|| operator
The || operator signifies the logical OR operation that appears in between two or
more valid UNIX commands. In this case, if the first command happens to be unsuccessful,
it will continue to execute next commands.
Syntax
$ command1 || command2|| …commandn
E.g.,
$ ls marks || date
ls: marks: No such file or directory
Thu Jan 29 [Link] IST 2009
|| operator-Output
[cse01@telnet ~]$ ls marks || date
ls: marks: No such file or directory
Thu Jan 29 [Link] IST 2009
Result
Thus the grouping commands were executed in UNIX and the Output was verified.
FILTERS
Aim:
To implement the various filter commands available in UNIX.
[Link] filter
24
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
A Filter is a device file that reads from the standard input and writes to the standard
Output in a particular format. In UNIX, this command displays the top ten lines of the file.
Syntax
$ head filename
E.g.,
$ head unix_file
Head filter-Output
[cse01@telnet ~]$ cat unix_file
This is a new file. This file is created for understanding the use command head [Link]
head filter is used for displaying the top ten lines of the [Link] default, a terminal displays
24 lines in one screen. The Output of the file is not [Link] is a test message.
[Link] filter
The tail command is the opposite of the head command. It displays 10 lines of a file
from the end of a file.
Syntax
$ tail filename
E.g.,
$ tail unix_file
Tail filter-Output
[cse01@telnet ~]$ tail unix_file
This file is created for understanding the use command head [Link] head filter is used
for displaying the top ten lines of the [Link] default, a terminal displays 24 lines in one
screen. The Output of the file is not [Link] is a test message.
[Link] command
The more command is used, if a file is too large for its contents to fit on the screen,
it will scroll the screen for the user view. It displays the first screenful information and
shows “-more-“ at the end of each page of the file that is being displayed. To continue
scrolling, press “Spacebar” instead of “Enter” key.
25
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Syntax
$ more filename
E.g.,
$ more unix_file
more command-Output
[cse01@telnet ~]$ more unix_file
This is a new file
This file is created for understanding the use command head filter.
The head filter is used for displaying the top ten lines of the file. By default, a terminal
displays 24 lines in one screen.
The Output of the file is not known. This is a test message.
[Link] command
The grep command is used to search and print specified patterns from a file. The
grep command is an abbreviation of “global regular expression and print”, where global
means “search for"
Syntax
$ grep pattern file
E.g.,
$ grep Asia countries
26
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
[Link] command
The sort command is used to sort the contents of a file.
Syntax
$ sort filename
E.g.,
$ sort countries
$ sort –r filename Sorts and displays the contents of the file in reverse order
$ sort –m filelist Merges sorted files in list
$ sort –n filename Sorts numerically
$ sort –d filename Alphanumeric sort
Sort command-Output
27
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Srilanka
China
Burma
Bangladesh
Uruguay
Uganda
Canada
28
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Uganda
Uruguay
[cse01@telnet ~]$ cat >> numbers
87
81
12
45
32
10
[Link] command
The uniq command is used to fetch one copy of the redundant records and writes it
to the standard Output.
Syntax
29
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
$ uniq filename
E.g.,
$ uiq salary
Uniq command-Output
[cse01@telnet ~]$ cat > salary
Priya 1000
Priya 1000
Sherin 2345
Sherin 2345
Brindha 9898
Brindha 9898
[cse01@telnet ~]$ cat salary
Priya 1000
Priya 1000
Sherin 2345
Sherin 2345
Brindha 9898
Brindha 9898
[cse01@telnet ~]$ uniq salary
Priya 1000
Sherin 2345
Brindha 9898
[Link] command
The cut command is used to select specified fields from a line of text.
Syntax
$ cut –c filename
E.g.,
$ cut –c1 salary
The above statement cuts only the first character of each line from the file salary.
Cut command-Output
[cse01@telnet ~]$ cat salary
Priya 1000
Priya 1000
Sherin 2345
Sherin 2345
Brindha 9898
Brindha 9898
30
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
[Link] command
The cmp command can be used to compare the files.
Syntax.
$ cmp file1 file2
E.g.,
$ cmp countries sortcountries
Cmp command-Output
[cse01@telnet ~]$ cmp countries sortcountries
countries sortcountries differ: byte 1, line 1
[Link]
The comm. Command is used to compare two sorted files and compares each line of
the first file with its corresponding line in the second. It displays a three columnar Output.
The first column curtains lives unique to the first file, while the second column shows the
lives unique to the second file. The third column displays the lines common to both files.
Syntax
$ comm. File1 file2
E.g.,
$ comm. Student Student1
Comm command – Output
[cse01@telnet ~]$ cat Student
Arul
Anban
Cherlie
David
Durga
Saravanan
[mtec11@telnet ~]$ cat Student1
31
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Arivu
Anban
Charlie
David
Suresh
[cse01@telnet ~]$ comm Student Student1
Arivu
Anban
Arul
Anban
Charlie
Cherlie
David
Durga
Saravanan
Suresh
[Link] command
The diff command can be used to display file differences but it also tells the lines in
which one file have to be changed to make the two files identical.
Syntax
$ diff file1 file2
E.g.,
$ diff Student Student1
diff command – Output
[cse01@telnet ~]$ diff Student Student1
1c1
< Arul
---
> Arivu
3c3
< Cherlie
---
> Charlie
5,6c5
< Durga
< Saravanan
---
32
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
> Suresh
Reference:
[Link]
Result
Thus the filter commands were executed and the Output was verified.
33
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Aim:
To write programs using the following system calls of UNIX operating system fork, exec,
getpid, exit, wait, close, stat, opendir, readdir
Introduction:
A computer program makes a system call when it makes a request to the operating
system’s kernel. System call provides the services of the operating system to the user
programs via Application Program Interface(API). It provides an interface between a
process and operating system to allow user-level processes to request services of the
operating system. System calls are the only entry points into the kernel system. All
programs needing resources must use system calls.
Definition:
A system call is the programmatic way in which a computer program requests a
service from the kernel of the operating system it is executed on. A system call is a way for
programs to interact with the operating system.
Theory:
When a program in user mode requires access to RAM or a hardware resource, it must
ask the kernel to provide access to that resource. This is done via something called a system call.
When a program makes a system call, the mode is switched from user mode to kernel
mode. This is called a context switch.
Then the kernel provides the resource which the program requested. After that, another
context switch happens which results in change of mode from kernel mode back to user mode.
Generally, system calls are made by the user level programs in the following situations:
Creating, opening, closing and deleting files in the file system.
Creating and managing new processes.
Creating a connection in the network, sending and receiving packets.
Requesting access to a hardware device, like a mouse or a printer.
Programs:
PROGRAM FOR SYSTEM CALLS OF UNIX OPERATING SYSTEM (Fork, Getpid, Exit)
#include<stdio.h>
#include<unistd.h>
34
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
main()
{
int pid,pid1,pid2;
pid=fork();
if(pid==-1)
{
printf(“ERROR IN PROCESS CREATION \n”);
exit(1);
}
if(pid!=0)
{
pid1=getpid();
printf(“\n the parent process ID is %d\n”, pid1);
}
else
{
pid2=getpid();
printf(“\n the child process ID is %d\n”, pid2);
}
}
OUTPUT:
[cse01@telnet ~]$ cc fork.c
[cse01@telnet ~]$ ./[Link]
35
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
}
else
wait(NULL);
printf("Parent Complete");
printf("Child Complete");
exit(0);
}
Output :
int main()
{
pid_t pid1,pid2,pid;
int status;
int i;
char buf[BUF_SIZE];
36
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output :
37
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
OUTPUT:
Thus [Link] opened for read or write access.
[Link] is currently empty.
38
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
#include<sys/stat.h>
int main(int argc,char *argv[])
{
if(argc!=2)
return 1;
struct stat filestat;
if(stat(argv[1],&filestat)<0)
return 1;
printf("\n information for %s\n",argv[1]);
printf(".......\n");
printf("file size:\t\t%d bytes\n",filestat.st_size);
printf("no of links:\t%d",filestat.st_nlink);
printf("file inode:\t\t%d\n",filestat.st_ino);
}
OUTPUT:
[cse01@telnet ~]$ cc exam.c
[cse01@telnet ~]$./[Link] msg.c
#include<stdio.h>
#include<dirent.h>
#include<sys/types.h>
main(int argc,char *argvs[])
{
DIR *dirname;
struct dirent *preaddir;
dirname=opendir(argvs[1]);
preaddir=readdir(dirname);
preaddir=readdir(dirname);
preaddir=readdir(dirname);
printf("open %s \n",argvs[1]);
printf("the first entry in the directory is %s\n",preaddir->d_name);
closedir(dirname);
}
39
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
OUTPUT:
[cse01@telnet ~]$ cc exam.c
[cse01@telnet ~]$./[Link] argvs
open argvs
the first entry in the directory is student
Answer: b
[Link] of the following system calls transforms executable binary file into a process ?
a) fork
b) exec
c) ioctl
d) longjmp
Answer: b
40
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
References:
[Link]
Result
Thus the programs using the following system calls of UNIX operating system fork,
exec, getpid, exit, wait, close, stat, opendir, readdir were executed and the Output was
verified.
41
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Introduction:
The UNIX operating system has for many years formed the backbone of the Internet,
especially for large servers and most major university campuses. However, a free version of
UNIX called Linux has been making significant gains against Macintosh and the Microsoft
Windows 95/98/NT environments, so often associated with personal computers.
Developed by a number of volunteers on the Internet such as the Linux group and the GNU
project, much of the open-source software is copyrighted, but available for free. This is
especially valuable for those in educational environments where budgets are often limited.
UNIX commands can often be grouped together to make even more powerful commands
with capabilities known as I/O redirection ( < for getting input from a file input and > for
outputing to a file ) and piping using | to feed the output of one command as input to the
next. Please investigate manuals in the lab for more examples than the few offered here.
Definition:
Unix (often spelled "UNIX," especially as an official trademark) is an operating
system that originated at Bell Labs in 1969 as an interactive time-sharing system. Ken
Thompson and Dennis Ritchie are considered the inventors of Unix. The name (pronounced
YEW-nihks) was a pun based on an earlier system, Multics. In 1974, Unix became the first
operating system written in the C language. Unix has evolved as a kind of large freeware
product, with many extensions and new ideas provided in a variety of versions of Unix by
different companies, universities, and individuals.
Theory:
To copy a file with the cp command pass the name of the file to be copied and then the
destination. In the following example the file [Link] is copied to a new file called [Link].
The cp command will also create the new file as part of the operation.
42
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
grep searches the named input FILEs (or standard input if no files are named, or if a single
hyphen-minus (-) is given as file name) for lines containing a match to the given PATTERN.
By default, grep prints the matching lines.
Simulation of ls command
Program:
#include<stdio.h>
#include<dirent.h>
main()
{
char dirname[10];
DIR*p;
struct dirent *d;
printf("Enter directory name\n");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
{
perror("Cannot find directory");
exit(-1);
}
while(d=readdir(p))
printf("%s\n",d->d_name);
}
OUTPUT:
[cse01@telnet ~]$ cc exe3.c
[cse01@telnet ~]$ ./[Link]
.[Link]
jes.c
s1.c
..
exp4b.c
m2.c
.bash_profile
ex2b.c
eee.c
t2a.c
43
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
si2.c
.[Link]
naspri.c
.[Link]
.bash_logout
.[Link]
.[Link]
.[Link]
.[Link]
.[Link]
adison.c
44
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
OUTPUT:
[cse01@telnet ~]$ cc ex3b1.c
[cse01@telnet ~]$ ./[Link] buf ex3b1.c
ex3b1.c
word is found
2. What happens if the destination file specified in cp command does not exist?
a) file will not be copied
b) an error will be produced
45
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Answer: c
References:
[Link]
Result
Thus the C programs to simulate UNIX commands like cp, ls, grep, etc were executed
and the Output was verified.
46
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Definition:
Shell script
A shell script is a file containing a list of commands to be executed by the Linux shell.
Shell script provides the ability to create your own customized Linux commands
Linux shell have sophisticated programming capabilities which makes shell script
powerful Linux tools
Theory:
Working with shell
Step1:
In the dollar prompt type
$ vi < file name>
Where vi is the editor ,it will open a new window in which you can type the program you
want
Step2:
After typing the program press ESC and : together then at the bottom of the vi screen you
can see i.e. prompt .In that type as wq which means write and quit i.e. the content what is
typed will be written and saved into that file that has been created
Step3:
Once wq is typed at the : prompt ,the prompt would change to $ symbol in which you have
to do the following
$ sh < file name >
sh – command is used to run the shell program
<file name> - is the name of the file for which the output is to be got
47
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Basically to print a text in the your shell programs echo command is used
Starting vi
You may use vi to open an already existing file by typing
vi filename
where "filename" is the name of the existing file. If the file is not in your current directory,
you must use the full pathname.
Or you may create a new file by typing
vi newname
where "newname" is the name you wish to give the new file.
To open a new file called "testvi," enter
vi testvi
On-screen, you will see blank lines, each with a tilde (~) at the left, and a line at the bottom
giving the name and status of the new file:
~
"testvi" [New file]
vi Modes
vi has two modes:
command mode 2
insert mode
In command mode, the letters of the keyboard perform editing functions (like moving the
cursor, deleting text, etc.). To enter command mode, press the escape <Esc> key.
In insert mode, the letters you type form words and sentences. Unlike many word
processors, vi starts up in command mode.
Entering Text
In order to begin entering text in this empty file, you must change from command mode to
insert mode. To do this, type
i
48
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Nothing appears to change, but you are now in insert mode and can begin typing text. In
general, vi's commands do not display on the screen and do not require the Return key to
be pressed.
Type a few short lines and press <Return> at the end of each line. If you type a long line,
you will notice the vi does not word wrap, it merely breaks the line unceremoniously at the
edge of the screen.
If you make a mistake, pressing <Backspace> or <Delete> may remove the error, depending
on your terminal type.
Moving the Cursor
To move the cursor to another position, you must be in command mode. If you have just
finished typing text, you are still in insert mode. Go back to command mode by pressing
<Esc>. If you are not sure which mode you are in, press <Esc> once or twice until you hear
a beep. When you hear the beep, you are in command mode.
The cursor is controlled with four keys: h, j, k, l.
Key Cursor Movement
--- ---------------
h left one space
j down one line
k up one line
l right one space
When you have gone as far as possible in one direction, the cursor stops moving and
you hear a beep. For example, you cannot use l to move right and wrap around to the next
line, you must use j to move down a line. See the section entitled "Moving Around in a File"
for ways to move more quickly through a file.
Basic Editing
Editing commands require that you be command mode. Many of the editing commands
have a different function depending on whether they are typed as upper- or lowercase.
Often, editing commands can be preceded by a number to indicate a repetition of the
command.
Deleting Characters
To delete a character from a file, move the cursor until it is on the incorrect letter, then type
49
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
x
The character under the cursor disappears. To remove four characters (the one under the
cursor and the next three) type
4x
To delete the character before the cursor, type
X (uppercase)
Deleting Words
To delete a word, move the cursor to the first letter of the word, and type
dw
This command deletes the word and the space following it.
To delete three words type
3dw
Deleting Lines
To delete a whole line, type
dd
The cursor does not have to be at the beginning of the line. Typing dd deletes the entire line
containing the cursor and places the cursor at the start of the next line. To delete two lines,
type
2dd
To delete from the cursor position to the end of the line, type
D (uppercase)
Replacing Characters
To replace one character with another:
Move the cursor to the character to be replaced.
Type r
Type the replacement character.
The new character will appear, and you will still be in command mode.
Replacing Words
To replace one word with another, move to the start of the incorrect word and type
cw
50
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
The last letter of the word to be replaced will turn into a $. You are now in insert mode and
may type the replacement. The new text does not need to be the same length as the
original. Press <Esc> to get back to command mode. To replace three words, type
3cw
Replacing Lines
To change text from the cursor position to the end of the line:
Type C (uppercase).
Type the replacement text.
Press <Esc>.
Inserting Text
To insert text in a line:
Position the cursor where the new text should go.
Type i
Enter the new text.
The text is inserted BEFORE the cursor.
4. Press <Esc> to get back to command mode.
Appending Text
To add text to the end of a line:
Position the cursor on the last letter of the line.
Type a
Enter the new text.
This adds text AFTER the cursor.
Press <Esc> to get back to command mode.
Opening a Blank Line
To insert a blank line below the current line, type
(lowercase)
To insert a blank line above the current line, type
O (uppercase)
Joining Lines
To join two lines together:
Put the cursor on the first line to be joined.
51
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Type J
To join three lines together:
Put the cursor on the first line to be joined.
Type 3J
Undoing
To undo your most recent edit, type
u
To undo all the edits on a single line, type
U (uppercase)
Undoing all edits on a single line only works as long as the cursor stays on that line. Once
you move the cursor off a line, you cannot use U to restore the line.
Moving Around in a File
There are shortcuts to move more quickly though a file. All these work in command mode.
Key Movement
--- --------
w forward word by word
b backward word by word
$ to end of line
0 (zero) to beginning of line
H to top line of screen
M to middle line of screen
L to last line of screen
G to last line of file
1G to first line of file
<Control>f scroll forward one screen
<Control>b scroll backward one screen
<Control>d scroll down one-half screen
<Control>u scroll up one-half screen
Moving by Searching
To move quickly by searching for text, while in command mode:
Type / (slash).
52
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
53
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
54
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
55
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
..
.
.
*) <error statement>;;
esac
Software Required:
telnet
Procedure:
Goto Command promand by typing run->telenet [Link]
Log in with their username and password & start typing vi [Link]
Compile & run by sh [Link]
Program:
Ex No 4.a DISPLAY WISHES BASED ON TIME
Aim:
To write a shell Program to display the wishes based on the time.
Algorithm:
1. Know the current time
2. Based on the time, display wishes as either good morning or good afternoon or
good evening or good night
3. Now, display both time and wishes
4. Terminate the process
Program
echo "Display wishes based on time"
echo "~~~~~~~~~~~~~~~~~~~~~~"
echo
d=`date +%H`
d1=`date +%c`
echo Time and Date at the moment is $d1
[ $d -gt 00 -a $d -lt 12 ] && echo "Good Morning"
[ $d -lt 16 -a $d -gt 12 ] && echo "Good Afternoon"
[ $d -gt 19 -a $d -lt 19 ] && echo "Good Evening"
[ $d -gt 19 -a $d -lt 23 ] && echo "Good Night"
echo [Link] again.
Output
[cse01@telnet ~]$ sh greetings
56
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Result:
Thus the time was found and a wish was displayed using the shell Program.
Aim:
To write a shell Program to find the bigger of two numbers.
Algorithm:
1. Start the Program
2. Read the 2 numbers a & b
3. Check whether ‘a’ is greater than ‘b’. If true, display ‘a’ is greater
4. Or display “b” is greater.
5. Terminate
Program
Output
[cse01@telnet ~]$ sh Biggest_Two
57
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Result:
Thus the biggest of 2 numbers was found using the shell Program and the result was
obtained.
ExNo:4.c Biggest among three numbers
Aim:
To write a shell Program to find the biggest among three numbers.
Algorithm:
1. Start the Program
2. Read the three numbers a, b, c
3. Check if a > b and a > c
4. If true, display ‘a’ is greater
5. Or check if b > c
6. If true, display ‘ b’ is greater
7. Or display ‘ c ‘ is greater
8. Terminate
Program
58
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output
Result:
Thus the biggest of 3 numbers was found using the shell Program.
Aim:
59
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Algorithm:
1. Start the Program
2. Read the two strings
3. Check if they are equal
4. If true, display ‘ the strings are equal’
5. Or display ‘the strings are not equal’
6. Terminate
Program
Output
60
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
String Comparison
~~~~~~~~~~~~~~
Enter The First String:Sunil
Enter The Second String:Sunil
The Given Strings Sunil and Sunil are equal
Result:
Thus two strings were compared using the shell Program and the Output was
verified.
Aim:
To write a shell program to perform arithmetic operations using switch statement
Algorithm:
1. Enter the input
2. Enter the choice
3. Perform corresponding arithmetic operation on the inputs
4. Display the result
Program
echo "Performing Arithmetic Manipulation"
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
echo -n "Enter the first no:"
read a
echo -n "Enter the second no:"
read b
echo "Arithmetic Operation - Menu"
echo "[Link]"
echo "[Link]"
echo "[Link]"
echo "[Link]"
echo "[Link]"
echo -n "Enter your Choice:"
read ch
case $ch in
1) echo " Option 1 Performs Addition" ;
61
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
c=`expr $a + $b`;
echo "The sum of $a and $b is $c";
exit ;;
2) echo " Option 2 Performs Subtraction" ;
c=`expr $a - $b`;
echo "The difference of $a and $b is $c";
exit ;;
3) echo " Option 3 Performs Multiplication" ;
c=`expr $a \* $b`;
echo "The product of $a and $b is $c";
exit ;;
4) echo " Option 4 Performs Division" ;
c=`expr $a / $b`;
echo "The Division of $a by $b is $c";
exit ;;
0) echo "You are exiting from the Arithmetic Manipulation" ;
echo "Thankyou. Visit again"
exit ;;
esac
Output
[cse01@telnet ~]$ sh Arithmetic_Manipulation
Performing Arithmetic Manipulation
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter the first no:12
Enter the second no:12
Arithmetic Operation - Menu
[Link]
[Link]
[Link]
[Link]
[Link]
Enter your Choice:1
Option 1 Performs Addition
The sum of 12 and 12 is 24
[cse01@telnet ~]$ sh Arithmetic_Manipulation
Performing Arithmetic Manipulation
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter the first no:12
Enter the second no:12
62
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
63
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Result:
Thus the arithmetic operations were performed using the shell Program.
Aim:
To write a shell Program for calculating the sum of ‘ n ‘ even numbers
Algorithm:
1. Read the value of ‘ n ‘
2. Initialize the variables ‘sum’ and ‘i’ as zero
3. Using while loop, increment the value if ‘i’ by 2
4. Calculate the value of sum
5. Display the result
6. Terminate
Program
echo -----------------------------
echo Sum of 'n' even numbers
echo -----------------------------
echo enter the value of n
read n
sum=0
i=2
while [ $i -le $n ]
do
sum=`expr $sum + $i`
64
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
i=`expr $i + 2`
done
echo The sum of even numbers upto $n is $sum
Output:
Result:
Thus the sum of ‘ n ‘ even numbers was found using the shell Program.
Aim:
To write a shell Program for calculating the sum of ‘ n ‘ natural numbers
Algorithm:
1. Read the value of ‘ n ‘
2. Initialize the variables ‘sum’ and ‘i’ as zero
3. Using while loop, increment the value if ‘i’
4. Calculate the value of sum
5. Display the result
6. Terminate
Program
echo --------------------------------
echo Sum of 'n' natural numbers
echo --------------------------------
echo Enter the value of n
read n
sum=0
i=0
65
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
while [ $i -le $n ]
do
sum=`expr $sum + $i`
i=`expr $i + 1`
done
echo The sum of first $n natural numbers is $sum
Output
Result:
Thus the sum of ‘ n ‘ natural numbers was found using the shell Program.
Aim:
To Write a Shell Program to generate the Fibonacci Series.
Algorithm
1. Read the maximum limit for generating the Fibonacci series.
2. Initialize two variables ‘a’ & ‘b’ to 0 and 1 respectively.
3. Print a
4. Print b
5. Perform c=a+b
6. Print c
7. Continue the procedure until the maximum limit read.
8. Stop when the maximum limit is exceeded.
Program:
echo ---------------------------
echo Generation of fibonaaci series
echo ---------------------------
a=0
66
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
b=1
c=0
echo "Enter the limit:"
read n
i=3
echo ------------------
echo "FIBONACCI SERIES"
echo ------------------
echo $a
echo $b
for((i=0;$i<$n;i++))
{
c=` expr $a + $b `
echo $c
a=$b
b=$c
}
Output:
[cse01@telnet ~]$ sh fib1
-----------------------------------
Generation of fibonaaci series
-----------------------------------
Enter the limit:
5
---------------------------
FIBONACCI SERIES
---------------------------
0
1
1
2
3
5
8
Result:
Thus the Shell Program to generate a Fibonacci series was written successfully and
the Output was verified.
67
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
References:
[Link]
Result:
Thus the Shell Program Using Vi Editor to Display Wishes Based on Time, Biggest of
Two Numbers, Biggest Among Three Numbers, String Comparison, Arithmetic Operations,
68
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Sum of N Even Numbers, Sum of N Natural Numbers, Generation of Fibonacci Series was
created and the output was displayed successfully.
Objective:
To learn about various CPU Scheduling techniques.
AIM:
To implement the various CPU Scheduling Algorithms
Introduction:
A Process Scheduler schedules different processes to be assigned to the CPU based
on particular scheduling algorithms. There are six popular process scheduling algorithms
which are:
First-Come, First-Served (FCFS) Scheduling
Shortest-Job-Next (SJN) Scheduling
Priority Scheduling
Definition:
CPU scheduling deals with the problem of deciding which of the processes in the
ready queue is to be allocated the CPU. There are many different CPU-scheduling
algorithms.
Theory:
First-Come, First-Served Scheduling:
With this scheme, the process that requests the CPU first is allocated the CPU first.
The implementation of the FCFS policy is easily managed with a FIFO queue. When a
process enters the ready queue, its PCB is linked onto the tail of the queue. When the CPU is
free, it is allocated to the process at the head of the queue. The running process is then
removed from the queue.
Process Burst Time
P1 24
P2 3
P3 3
If the processes arrive in the order P1, P2, P3, and are served in FCFS order, we get
the result shown in the following Gantt chart, which is a bar chart that illustrates a
particular schedule, including the start and finish times of each of the participating
processes:
69
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Waiting Time:
The waiting time is 0 milliseconds for process P1, 24 milliseconds for process P2, and 27
milliseconds for process P3. Thus, the average waiting time is (0+ 24 + 27)/3 = 17
milliseconds.
Shortest-Job-First Scheduling:
A different approach to CPU scheduling is the shortest-job-first (SJF) scheduling
algorithm. This algorithm associates with each process the length of the process’s next CPU
burst. When the CPU is available, it is assigned to the process that has the smallest next CPU
burst. If the next CPU bursts of two processes are the same, FCFS scheduling is used to
break the tie.
Process Burst Time
P1 6
P2 8
P3 7
P4 3
Using SJF scheduling, we would schedule these processes according to the following Gantt
chart:
Waiting Time:
The waiting time is 3 milliseconds for process P1, 16 milliseconds for process P2, 9
milliseconds for process P3, and 0 milliseconds for process P4. Thus, the average waiting
time is (3 + 16 + 9 + 0)/4 = 7 milliseconds. By comparison, if we were using the FCFS
scheduling scheme, the average waiting time would be 10.25 milliseconds.
Priority Scheduling:
The SJF algorithm is a special case of the general priority-scheduling algorithm.
Apriority is associated with each process, and the CPUis allocated to the process with the
highest priority. Equal-priority processes are scheduled in FCFS order. An SJF algorithm is
simply a priority algorithm where the priority (p) is the inverse of the (predicted) next CPU
burst. The larger the CPU burst, the lower the priority, and vice versa. Some systems use
low numbers to represent low priority; others use low numbers for high priority.
Round-Robin Scheduling:
70
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
71
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
struct process
{
int pno;
int btime;
int wtime;
int ttime;
int rrtime;
int pri;
}p[10],temp;
printf("FIFO scheduling\n");
tot_wt=tot_tn=0;
printf("Enter the no of process\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i].pno=i+1;
printf("Enter the burst time of process %d\n",i+1);
scanf("%d",&p[i].btime);
}
p[0].wtime=0;
p[0].ttime=p[0].btime;
tot_tn=p[0].btime;
for(i=1;i<n;i++)
{
p[i].wtime=p[i-1].ttime;
p[i].ttime=p[i].wtime+p[i].btime;
tot_wt+=p[i].wtime;
tot_tn+=p[i].ttime;
}
printf("Process no \tBurst time \t Waiting time \tTurnaroundtime\n");
for(i=0;i<n;i++)
printf("%d\t\t%d\t\t%d\t\t%d\n",p[i].pno,p[i].btime,p[i].wtime,p[i].ttime);
printf("Avg waiting time %f\n",tot_wt/n);
printf("Avg turnaround time %f\n",tot_tn/n);
}
"exp4.c" 41L, 817C written
Output :
[cse01@telnet ~]$ cc exp4.c
[cse01@telnet ~]$ ./[Link]
72
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
FIFO scheduling
Enter the no of process
5
Enter the burst time of process 1
2
Enter the burst time of process 2
1
Enter the burst time of process 3
3
Enter the burst time of process 4
4
Enter the burst time of process 5
3
Process no Burst time Waiting time Turnaroundtime
1 2 0 2
2 1 2 3
3 3 3 6
4 4 6 10
5 3 10 13
Avg waiting time 4.200000
Avg turnaround time 6.800000
Result:-
Thus the c program to implement the FCFS scheduling algorithm was executed and
the output was verified successfully.
73
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
float tot_wt,tot_tn;
struct process
{
int pno;
int btime;
int wtime;
int ttime;
int rrtime;
int pri;
}p[10],temp;
printf("SJF scheduling\n");
tot_wt=tot_tn=0;
printf("Enter the no of process\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i].pno=i+1;
printf("Enter the burst time of process %d\n",i+1);
scanf("%d",&p[i].btime);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(p[i].btime>p[j].btime)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
p[0].wtime=0;
p[0].ttime=p[0].btime;
tot_tn=p[0].btime;
for(i=1;i<n;i++)
{
p[i].wtime=p[i-1].ttime;
p[i].ttime=p[i].wtime+p[i].btime;
tot_wt+=p[i].wtime;
74
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
tot_tn+=p[i].ttime;
}
printf("Process no \tBurst time \t Waiting time \tTurnaroundtime\n");
for(i=0;i<n;i++)
printf("%d\t\t%d\t\t%d\t\t%d\n",p[i].pno,p[i].btime,p[i].wtime,p[i].ttime);
printf("Avg waiting time %f\n",tot_wt/n);
printf("Avg turnaround time %f\n",tot_tn/n);
}
Result:-
Thus the c program for implementation of SJF scheduling algorithm was executed
and the output was verified successfully.
75
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
76
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
p[i]=p[j];
p[j]=temp;
}}}
p[0].wtime=0;
p[0].ttime=p[0].btime;
tot_tn=p[0].btime;
for(i=1;i<n;i++)
{
p[i].wtime=p[i-1].ttime;
p[i].ttime=p[i].wtime+p[i].btime;
tot_wt+=p[i].wtime;
tot_tn+=p[i].ttime;
}
printf("Process no \tPriority\tBurst time \tWaiting time\tTurnaroundtime\n");
for(i=0;i<n;i++)
printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\
n",p[i].pno,p[i].pri,p[i].btime,p[i].wtime,p[i].ttime);
printf("Avg waiting time %f\n",tot_wt/n);
printf("Avg turn around time %f\n",tot_tn/n);
}
Output :
[cse01@telnet ~]$ cc exp5a.c
[cse01@telnet ~]$ ./[Link]
Priority scheduling
Enter the no of process
5
Enter the burst time of process 1
1
Enter the priority if the process1
5
Enter the burst time of process 2
2
Enter the priority if the process2
4
Enter the burst time of process 3
3
Enter the priority if the process3
3
Enter the burst time of process 4
77
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
2
Enter the priority if the process4
2
Enter the burst time of process 5
1
Enter the priority if the process5
1
Process no Priority Burst time Waiting time Turnaroundtime
1 5 1 0 1
5 1 1 1 2
4 2 2 2 4
2 4 2 4 6
3 3 3 6 9
Avg waiting time 2.600000
Avg turnaround time 4.400000
Result:-
Thus the c program for implementation of Priority scheduling algorithm was
executed and the output was verified successfully.
78
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
int wtime;
int ttime;
int rrtime;
int pri;
}p[10],temp;
ptm=0;
printf("RR Scheduling\n");
tot_wt=tot_tn=0;
printf("Enter the no of processes\n");
scanf("%d",&n);
printf("Enter the Time slice\n");
scanf("%d",&ts);
for(i=0;i<n;i++)
{
p[i].pno=i+1;
p[i].wtime=p[i].ttime=0;
printf("Enter the Burst time of process %d\n",i+1);
scanf("%d",&p[i].btime);
p[i].rrtime=p[i].btime;
}
do
{
flag=0;
for(i=0;i<n;i++)
{
count=p[i].btime;
if(count>0)
{
flag=1;
count=(count>=ts)?ts:count;
printf("Process %d from %d to %d\n",p[i].pno,ptm,ptm+count);
p[i].wtime+=ptm-p[i].ttime;
ptm=ptm+count;
p[i].ttime=ptm;
p[i].btime-=count;
}
}
}while(flag);
for(i=0;i<n;i++)
79
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
{
tot_wt+=p[i].wtime;
tot_tn+=p[i].ttime;
}
printf("Process no \tBurst time \tWaiting time \tTurnaroundtime\n");
for(i=0;i<n;i++)
printf("%d\t\t%d\t\t%d\t\t%d\n",p[i].pno,p[i].rrtime,p[i].wtime,p[i].ttime);
printf("Avg waiting time %f\n",tot_wt/n);
printf("Avg turn around time %f\n",tot_tn/n);
}
Output :
[cse01@telnet ~]$ cc exp5b.c
[cse01@telnet ~]$ ./[Link]
RR Scheduling
Enter the no of processes
3
Enter the Time slice
25
Enter the Burst time of process 1
1
Enter the Burst time of process 2
2
Enter the Burst time of process 3
3
Process 1 from 0 to 1
Process 2 from 1 to 3
Process 3 from 3 to 6
Process no Burst time Waiting time Turnaroundtime
1 1 0 1
2 2 1 3
3 3 3 6
Avg waiting time 1.333333
Avg turn around time 3.333333
80
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
References:
81
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System
Concepts”, 9th Edition, John Wiley and Sons Inc., 2012.
Result:-
Thus the c program for implementation of Round Robin scheduling algorithm was
executed and the output was verified successfully.
EX No: 6 Implementation of Semaphores
Objective:
To learn about how to control the multiple access to resources.
Aim:
To implement the Producer and Consumer Problem using semaphores
Introduction:
A semaphore, in its most basic form, is a protected integer variable that can
facilitate and restrict access to shared resources in a multi-processing environment. The
two most common kinds of semaphores are counting semaphores and binary
semaphores.
Definition:
In computer science, a semaphore is a variable or abstract data type that is used to
control access to a common resource by multiple processes in a concurrent system such as
a multiprogramming operating system.
Theory:
Critical Section:
Consider a system consisting of n processes {P0, P1, ..., Pn−1}. Each process has a
segment of code, called a critical section, in which the process may be changing common
variables, updating a table, writing a file, and so on. The important feature of the system is
that, when one process is executing in its critical section, no other process is allowed to
execute in its critical section. That is, no two processes are executing in their critical
sections at the same time. The critical-section problem is to design a protocol that the
processes can use to cooperate. Each process must request permission to enter its critical
section. The section of code implementing this request is the entry section. The critical
section may be followed by an exit section. The remaining code is the remainder section.
A solution to the critical-section problem must satisfy the following three requirements:
1. Mutual exclusion.
82
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
2. Progress.
3. Bounded waiting.
Semaphores:
A more robust tool that can behave similarly to a mutex lock but can also provide
more sophisticated ways for processes to synchronize their activities. A semaphore S is an
integer variable that, apart from initialization, is accessed only through two standard atomic operations:
wait() and signal().
wait(S) { signal(S) {
while (S <= 0); // busy wait S++;
S--; }
}
Semaphore Usage:
Types:
Operating systems often distinguish between counting and binary semaphores. The
value of a counting semaphore can range over an unrestricted domain. The value of a
binary semaphore can range only between 0 and 1. Thus, binary semaphores behave
similarly to mutex locks. In fact, on systems that do not provide mutex locks, binary
semaphores can be used instead for providing mutual exclusion.
Semaphore Implementation:
To overcome the need for busy waiting, we can modify the definition of the wait()
and signal() operations as follows: When a process executes the wait() operation and finds
that the semaphore value is not positive, it must wait. However, rather than engaging in
busy waiting, the process can block itself. The block operation places a process into a
waiting queue associated with the semaphore, and the state of the process is switched to
the waiting state. Then control is transferred to the CPU scheduler, which selects another
process to execute.
A process that is blocked, waiting on a semaphore S, should be restarted when some
other process executes a signal() operation. The process is restarted by a wakeup()
operation, which changes the process from the waiting state to the ready state. The process
is then placed in the ready queue.
The block() operation suspends the process that invokes it. The wakeup(P)
operation resumes the execution of a blocked process P. These two operations are
provided by the operating system as basic system calls.
It is critical that semaphore operations be executed atomically. We must guarantee
that no two processes can execute wait() and signal() operations on the same semaphore at
the same time.
83
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Software Required:
Turbo C or telnet.
Procedure:
Goto turbo C
Compile the C program by “compile”.
Run the C program by “run”.
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
Algorithm:
1. Start
2. Initialize the semaphore variable S
3. In the producer function,
3a) while s ==1 do nothing
3b) Produce the value
3c) Assign s=1
3d) Return
4. In the Consumer function
4a) While s==0 do nothing
4b) Display the consumed value
4c) Assign s=0
4d) Return
5. Create threads for producer and consumer function to make it run concurrently
6. Stop
PROGRAM:
#include<stdio.h>
typedef int semaphore;
semaphore mutex = 1;
semaphore empty;
semaphore full = 0;
void main()
{
int option;
int n;
char buf[10][5];
84
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
85
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
break;
}
}
while(option<=3);
}
Output :
[cse01@telnet ~]$ ./[Link]
Producer Consumer Relationship
Enter the Buffer Size:2
[Link] [Link] [Link]
Enter ur choice:1
Item to be Produced:doss
Enter ur choice:1
Item to be Produced:maran
Enter ur choice:1
Producer cannot produce, Buffer is full
Enter ur choice:2
Consumer wants to be consumer maran
Enter ur choice:2
86
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Enter ur choice:3
References:
87
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
Result:-
Thus the c program for implementation of producer & consumer problem using
semaphores was executed and the output was verified successfully.
88
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Shared memory can be faster than message passing, since message-passing systems are
typically implemented using system calls and thus require the more time-consuming task
of kernel intervention. In shared-memory systems, system calls are required only to
establish shared memory regions. Once shared memory is established, all accesses are
treated as routine memory accesses, and no assistance from the kernel is required.
Shared-Memory Systems:
Interprocess communication using shared memory requires communicating
processes to establish a region of shared memory. Typically, a shared-memory region
resides in the address space of the process creating the shared-memory segment. Other
processes that wish to communicate using this shared-memory segment must attach it to
their address space.
Shared memory requires that two or more processes agree to remove this
restriction. They can then exchange information by reading and writing data in the shared
areas.
A producer process produces information that is consumed by a consumer
process. One solution to the producer–consumer problem uses shared memory. To allow
producer and consumer processes to run concurrently, we must have available a buffer of
items that can be filled by the producer and emptied by the consumer.
Software Required:
Turbo C or telnet.
89
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Procedure:
Goto turbo C
Compile the C program by compile.
Run the C program by run.
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
Algorithm:-
1. Start the program
[Link] two process are created,the string Shmid is assigned in shmsize 27 which
then read to the bult variable,another string is to given in another variable a.
3 These two strings are compared if equal to 0,else not equal.
4. Stop the program.
Program:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSIZE 27
int main()
{
int shmid;
int *shm;
int *n;
if(fork() == 0) {
shmid = shmget(2009, SHMSIZE, 0);
shm = shmat(shmid, 0, 0);
n = shm;
int i;
for(i=0; i<5; i++) {
printf("Enter number<%i>: ", i);
scanf("%d", n++);
}
printf ("Child wrote <%d>\n",shm);
90
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
shmdt(shm);
}
else {
wait();
int *s;
shmid = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);
shm = shmat(shmid, 0, 0);
s = shm;
wait(NULL);
printf ("Parent reads <%d>\n",shm) ;
shmdt(shm);
shmctl(shmid, IPC_RMID, NULL);
}
return 0;
}
And the output is just this line:
Enter number<1>:
And if I entered a number, let's say 25, it outputs this:
Parent reads <r>
r: random -ve number changes every time I execute the code
Aim:-
To write a c program to implement the Inter process communication using pipes.
Algorithm:-
1. Start the program
2. The two process are created,the string INER is assigned in pipefd [1] which then
read to the bult variable,another string is to given in another variable a.
3. These two strings are compared if equal to 0, else not equal.
4. Stop the program.
Program:
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/ipc.h>
main()
{
int n,pid1,pid2,pipefd[2];
char bult[10],a[30];
91
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
if(pipe(pipefd)<0)
{
printf("ERROR");
}
printf("Enter the String:");
scanf("%s",a);
pid1 = fork();
if(pid1!=0)
{
write(pipefd[1],"INER",30);
}
pid2 = fork();
if(pid2 == 0)
{
n = read(pipefd[0],bult,sizeof(bult));
if(strcmp(a,bult) == 0)
{
printf("String are Equal");
}
else
{
printf("String are not Equal");
}
}
exit(0);
}
Output:
[cse01@telnet ~]$ cc ex6a.c
[cse01@telnet ~]$ ./[Link]
Enter the String:DOSS MARAN
String are not Equal
[cse01@telnet ~]$ ./[Link]
Enter the String: INER
String are Equal
92
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
93
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
94
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
#include<sys/ipc.h>
#include<sys/msg.h>
#include<string.h>
main()
{
int pid,qid,len,ppid;
struct
{
char text[20];
}
mess1,mess2;
strcpy([Link],"to child");
qid=msgget((key_t)40,IPC_CREAT/0666);
printf("The QUEUE id is %d\n",qid);
len=strlen([Link]);
if(msgsnd(qid,&mess1,len,0)==1)
{
printf("\n message Transaction is failed");
exit(1);
}
pid=fork();
if(pid==0)
{
printf("\n The parent process ID is:%d",getppid());
}
printf("\n The child process ID is :%d\n",getpid());
if(msgrcv(qid,&mess2,len,0,0)==1)
{
printf("Message is not received\n");
exit(1);
}
else
{
printf("\n child processor");
printf("%s\n",[Link]);
strcpy([Link],"To parent");
}
if(msgsnd(qid,&mess2,len,0)==1)
{
printf("\n message is not transmitted");
95
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
exit(1);
}
else
{
if(msgrcv(qid,&mess1,len,0,0)==1)
{
printf("Message is not received\n");
exit(1);
}
printf("\n parent processor");
printf("%s\n",[Link]);
}
}
Output:
[cse01@telnet ~]$ cc ex6c.c
[cse01@telnet ~]$ ./[Link]
The QUEUE id is -1
The parent process ID is:20128
The child process ID is :20129
child processorto child
parent processorTo parent
The child process ID is :20128
child processorto child
parent processorTo parent
96
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
97
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Result:-
Thus the c program for implementation of shared memory and Inter process
communication using pipes, signals and message queue was executed and the output was
verified successfully.
98
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
Algorithm:
Safety algorithm
1. Start
2. Initialize a temporary vector W (Work) to equal the available vector A.
3. Find an index i (row i) such that
Need i = W
If no such row exists, the system will deadlock, since no process can run to completion.
4. If such a row is found, mark this process as finished, and add all its resources to W
Vector i,
W = W + Ci
Go to step 2, until either all processes are marked terminated (in this case initial state is
safe), or
until a deadlock occurs, in which the state is not safe.
PROGRAM:
#include<stdio.h>
void main()
100
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
{
int r[1][10],av[1][10];
int all[10][10],max[10][10],ne[10][10],w[10],safe[10];
int i=0,j=0,k=0,l=0,np=0,nr=0,count=0,cnt=0;
clrscr();
printf("enter the number of processes in a system");
scanf("%d",&np);
printf("enter the number of resources in a system");
scanf("%d",&nr);
for(i=1;i<=nr;i++)
{
printf("\n enter the number of instances of resource R%d " ,i);
scanf("%d",&r[0][i]);
av[0][i]=r[0][i];
}
for(i=1;i<=np;i++)
for(j=1;j<=nr;j++)
all[i][j]=ne[i][j]=max[i][j]=w[i]=0;
printf(" \nEnter the allocation matrix");
for(i=1;i<=np;i++)
{
printf("\n");
for(j=1;j<=nr;j++)
{
scanf("%d",&all[i][j]);
av[0][j]=av[0][j]-all[i][j];
}
}
printf("\nEnter the maximum matrix");
for(i=1;i<=np;i++)
{
printf("\n");
for(j=1;j<=nr;j++)
{
scanf("%d",&max[i][j]);
}
}
for(i=1;i<=np;i++)
{
for(j=1;j<=nr;j++)
101
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
{
ne[i][j]=max[i][j]-all[i][j];
}
}
for(i=1;i<=np;i++)
{
printf("pocess P%d",i);
for(j=1;j<=nr;j++)
{
printf("\n allocated %d\t",all[i][j]);
printf("maximum %d\t",max[i][j]);
printf("need %d\t",ne[i][j]);
}
printf("\n_________________________\n");
}
printf("\nAvailability");
for(i=1;i<=nr;i++)
printf("R%d %d\t",i,av[0][i]);
printf("\n____________");
printf("\n safe sequence");
for(count=1;count<=np;count++)
{
for(i=1;i<=np;i++)
{
cnt=0;
for(j=1;j<=nr;j++)
{
if(ne[i][j]<=av[0][j] && w[i]==0)
cnt++;
}
if(cnt==nr)
{
k++;
safe[k]=i;
for(l=1;l<=nr;l++)
av[0][l]=av[0][l]+all[i][l];
printf("\n P%d ",safe[k]);
printf("\t Availability");
for(l=1;l<=nr;l++)
102
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
printf("R%d %d\t",l,av[0][l]);
w[i]=1;
}
}
getch();
}
Output:
[cse01@telnet ~]$ cc exd.c
[cse01@telnet ~]$ ./[Link]
Enter the no. of process and resources:3
10
Enter pname,requested,allocated 1 5 3
Enter pname,requested,allocated 2 3 2
Enter pname,requested,allocated 3 2 2
Remaining:3
Pname Allocated Nested Released
1 5 0 6
2 3 0 8
3 2 0 10
SAFE STATE
Do you want to continue:1 for yes and 0 for no1
Enter the no. of process and resources:3 10
Enter pname,requested,allocated 1 5 5
Enter pname,requested,allocated 2 4 4
Enter pname,requested,allocated 3 5 4
Remaining:-3
Pname Allocated Needed Released
UNSAFE
Do you want to continue:1 for yes and 0 for no0
103
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
4. Circular wait
3. Explain Deadlock Avoidance.
The resource-allocation-graph algorithm is not applicable to a resource allocation
system with multiple instances of each resource type. The deadlock avoidance algorithm is
less efficient than the resource-allocation graph scheme. This algorithm is commonly
known as the banker’s algorithm.
4. Explain the Data Structuresin the banker’s algorithm.
Available:
A vector of length m indicates the number of available resources of each type.
Max:
An n × m matrix defines the maximum demand of each process
Allocation:
An n × m matrix defines the number of resources of each type currently allocated to
each process.
Need:
An n × m matrix indicates the remaining resource need of each process.
Safety Algorithm
Resource-Request Algorithm
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
104
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Result:-
Thus the c program for the implementation of Banker’s algorithm for deadlock
avoidance was executed and the output was verified successfully.
The algorithm employs several time-varying data structures that are similar to
those used in the banker’s algorithm:
• Available.
A vector of length m indicates the number of available resources of each type.
• Allocation.
An n × m matrix defines the number of resources of each type currently allocated to
each process.
• Request.
An n × m matrix indicates the current request of each process. If Request[i][j]
equals k, then process Pi is requesting k more instances of resource type Rj.
To simplify notation, we treat the rows in the matrices Allocation and Request as
vectors; we refer to them as Allocationiand [Link] detection algorithm described
here simply investigates every possible allocation sequence for the processes that remain
to be completed.
Let Work and Finish be vectors of length m and n, respectively.
1. Initialize Work = Available. For i = 0, 1, ...,n–1, if Allocationi_= 0, then Finish[i] =
false. Otherwise, Finish[i] = true.
2. 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, 0≤i<n, then the system is in a deadlocked
[Link], if Finish[i] == false, then process Pi is deadlocked.
Software Required:
Turbo C or telnet.
106
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Procedure:
Goto turbo C
Compile the C program by compile.
Run the C program by run.
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int found,flag,l,p[4][5],tp,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
clrscr();
printf("enter total no of processes");
scanf("%d",&tp);
printf("enter clain matrix");
for(i=1;i<=4;i++)
for(j=1;j<=5;j++)
{
107
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
scanf("%d",&c[i][j]);
}
printf("enter allocation matrix");
for(i=1;i<=4;i++)
for(j=1;j<=5;j++)
{
scanf("%d",&p[i][j]);
}
printf("enter resource vector:\n");
for(i=1;i<=5;i++)
{
scanf("%d",&r[i]);
}
printf("enter availability vector:\n");
for(i=1;i<=5;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}
for(i=1;i<=4;i++)
{
sum=0;
for(j=1;j<=5;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=1;i<=4;i++)
{
for(l=1;l<k;l++)
if(i!=m[l])
{
flag=1;
for(j=1;j<=5;j++)
if(c[i][j]>temp[j])
108
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
{
flag=0;
break;
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=1;j<=5;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are:");
for(j=1;j<=tp;j++)
{
found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0)
printf("%d\t",j);
}
getch();
}
INPUT:
enter total no. of processes : 4
enter claim matrix :
01001
00101
00001
10101
enter allocation matrix :
10110
11000
00010
00000
109
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
OUTPUT :
deadlock causing processes are : 1 2
#include<stdio.h>
struct bankeralgm
{
int alloc,req,diff;
char pname[10];
}p[10],temp;
int main()
{
int c;
do
{
int i,j,flag=0,total=0,process,resource,remaining;
printf("\n enter the no of process & resources:");
scanf("%d%d",&process,&resource);
for(i=1;i<=process;i++)
{
printf("\n enter PNAME,REQUESTED,ALLOCATED");
scanf("%s%d%d",&p[i].pname,&p[i].req,&p[i].alloc);
p[i].diff=p[i].req-p[i].alloc;
total=total+p[i].alloc;
}
for(i=1;i<=process;i++)
{
for(j=i+1;j<=process;j++)
{
if(p[i].diff>p[j].diff)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
110
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
}
}
}
remaining=resource-total;
printf("\n remaining%d",remaining);
printf("\n pNAME \t ALLOCATED \t NEEDED \t RELEASED");
for(i=1;i<=process;i++)
{
if(remaining==p[i].diff)
{
p[i].alloc=remaining+p[i].alloc;
p[i].req=p[i].req-p[i].alloc;
remaining=p[i].alloc;
printf("\n%s\t%d\t\t%d\t%d",p[i].pname,
p[i].alloc,p[i].req,remaining);
}
else if(remaining>p[i].diff)
{
p[i].alloc=p[i].diff+p[i].alloc;
p[i].req=p[i].req-p[i].alloc;
remaining=remaining-p[i].diff+p[i].alloc;
printf("\n%s%t%d\t\t%d\t%d",p[i].pname,
p[i].req,remaining);
}
else
{
printf("\n UNSAFE STATE");
flag=1;
break;
}
}
if(flag==0)
printf("\n safe state");
printf("\n do you want to continue(1 for yes/0 for no:");
}while(c==1);
}
}
111
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output:
[cse01@telnet ~]$ cc ex10d.c
[cse01@telnet ~]$ ./[Link]
112
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
3. What is Several Instances of a Resource Type: The wait-for graph scheme is not
applicable to a resource-allocation system with multiple instances of each resource
type. We turn now to a deadlock detection algorithm that is applicable to such a
system.
4. Define Deadlock Recovery.
When a detection algorithm determines that a deadlock exists, several alternatives
are available. There are two options for breaking a deadlock.
Process Termination:
o Abort all deadlocked processes.
o Abort one process at a time until the deadlock cycle is eliminated.
Resource Preemption:
o Selecting a victim.
o Rollback.
o Starvation.
5. Write the three ways to deal the deadlock problem.
• We can use a protocol to prevent or avoid deadlocks, ensuring that the
system will neverenter a deadlocked state.
• We can allow the system to enter a deadlocked state, detect it, and recover.
• We can ignore the problem altogether and pretend that deadlocks never
occur in the system.
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
Result:-
Thus the c program for the implementation of Banker’s algorithm for deadlock
detection was executed and the output was verified successfully.
113
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
114
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Synchronization
A situation where several processes access and manipulate the same data
concurrently and the outcome of the execution depends on the particular order in which
the access takes place, is called a race condition. To guard against the race condition
above, we need to ensure that only one process at a time can be manipulating a variable. To
make such a guarantee, we require that the processes be synchronized in some way.
Software Required:
Turbo C or telnet.
Procedure:
Goto turbo C
Compile the C program by compile.
Run the C program by run.
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
Algorithm:
1. Start the program.
2. Create two threads and a counter is maintained in start of these threads.
3. A mutex is initialized in the beginning of the main function.
4. The same mutex is locked in the ‘doSomeThing()’ function while using the shared
resource ‘counter’.
5. At the end of the function ‘doSomeThing()’ the same mutex is unlocked.
115
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
6. At the end of the main function when both the threads are done, the mutex is
destroyed.
Program:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
if(pthread_equal(id,tid[0]))
{
printf("\n First thread processing\n");
}
else
{
printf("\n Second thread processing\n");
}
for(i=0; i<(0xFFFFFFFF);i++);
return NULL;
}
int main(void)
{
int i = 0;
int err;
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
116
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
i++;
}
sleep(5);
return 0;
}
OUTPUT:
$ ./threads
Thread created successfully
First thread processing
Thread created successfully
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int counter;
for(i=0; i<(0xFFFFFFFF);i++);
117
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
return NULL;
}
int main(void)
{
int i = 0;
int err;
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}
OUTPUT:
$ ./tgsthreads
Job 1 started
Job 2 started
Job 2 finished
Job 2 finished
118
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
OUTPUT:
Creating thread 0
Creating thread 1
Creating thread 2
Creating thread 3
Creating thread 4
Creating thread 5
Creating thread 6
Creating thread 7
Thread 0: English: Hello World! Sum=0
Thread 1: French: Bonjour, le monde! Sum=1
Thread 2: Spanish: Hola al mundo Sum=3
Thread 3: Klingon: Nuq neH! Sum=6
Thread 4: German: Guten Tag, Welt! Sum=10
Thread 5: Russian: Zdravstvytye, mir! Sum=15
Thread 6: Japan: Sekai e konnichiwa! Sum=21
119
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
Result:-
120
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Objective:
To know about Memory allocation methods.
Aim:
To implement memory allocation methods for fixed partition ,First Fit , Worst Fit and
Best Fit
Introduction:
This method was originally used by the IBM OS/36operating syste(calledMFT)but is
no longer in [Link] method described next isa generalization of the fixed-partition
scheme(calledMVT); it is used primarily in batch environments. Many of theideaspresented
here are also applicable to a time-sharing environment in whichpure segmentation is used
for memory management (Section 8.4).In thevariable-partitionscheme, the operating
system keeps a tableindicating which parts of memory are available and whichareoccupied.
Initially, all memory is available for user processes and is considered onelarge block of
available memory, ahole. Eventually, as you will see, memorycontains a set of holes of
various sizes.
Definition:
One of the simplest methods for allocating memory is to divide memory into several
fixed-sized partitions. Each partition may contain exactly one process. Thus, the degree of
multiprogramming is bound by the number of partitions. In this multiple- partition method
when a partition is free, a process is selected from the input queue and is loaded into the
free partition. When the process terminates, the partition becomes available for another
process.
Theory:
1. First Fit: In the first fit, partition is allocated which is first sufficient from the top of Main
Memory.
2. Best Fit Allocate the process to the partition which is first smallest sufficient partition
among the free available partition.
3. Worst Fit Allocate the process to the partition which is largest sufficient among the
freely available partitions available in the main memory.
Program:
121
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
FIRST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - Worst Fit"); printf("\nEnter the number of
blocks:"); scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i];
if(temp>=0)
if(highest<temp)
{
ff[i]=j;
highest=temp;
}
}
}
frag[i]=highest;
bf[ff[i]]=1;
highest=0;
122
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement"); for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
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 3 7 6
2 4 1 5 1
WORST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
123
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\
tFragement"); for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
OUTPUT
Fragme
File No File Size Block No Block Size nt
124
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
1 1 1 5 4
2 4 3 7 3
BEST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
clrscr();
125
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock Size\
tFragment"); for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
OUTPUT
Fragme
File No File Size Block No Block Size nt
1 1 2 2 1
2 4 1 5 1
600 115
350 500
200 358
750 200
125 375
126
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
First Fit:
300
115
600
500
350
358
200
200
750
375
125
Worst Fit:
115
300
600 500
350
358
200
200
750
375
125
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
Result:-
Thus the c program for Implementation of Memory Allocation Methods for fixed
partition was executed and the output was verified successfully.
127
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Objective:
To know about paging concept.
To learn how to implement paging techniques.
Aim:
To implement memory allocation with pages.
Introduction:
The basic method for implementing paging involves breaking physical memory into
fixed-sized blocks called frames and breaking logical memory into blocks of the same size
called pages.
Definition:
Paging is another memory-management scheme that offers this advantage.
However, paging avoids external fragmentation and the need for compaction, whereas
segmentation does not. It also solves the considerable problem of fitting memory chunks of
varying sizes onto the backing store.
Theory:
Page Table: Every address generated by the CPU is divided into two parts: a page
number (p) and a page offset (d). The page number is used as an index into a page table.
The page table contains the base address of each page in physical memory.
Advantages:
When we use a paging scheme, we have no external fragmentation: any free frame can be
allocated to a process that needs it. However, we may have some internal fragmentation.
Notice that frames are allocated as units. If the memory requirements of a process do not
happen to coincide with page boundaries, the last frame allocated may not be completely
full.
Allocation:
When a process arrives in the system to be executed, its size, expressed in pages, is
examined. Each page of the process needs one frame. Thus, if the process requires n pages,
at least n frames must be available in memory. If n frames are available, they are allocated
to this arriving process. The first page of the process is loaded into one of the allocated
frames, and the frame number is put in the page table for this process. The next page is
loaded into another frame; its frame number is put into the page table, and so on.
Translation Look aside Buffer:
128
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Use a special, small, fast lookup hardware cache called a translation look-aside buffer
(TLB) only a few of the page-table entries. When a logical address is generated by the CPU,
its page number is presented to the TLB. If the page number is found, its frame number is
immediately available and is used to access memory.
One additional bit is generally attached to each entry in the page table: a valid–invalid bit.
When this bit is set to valid, the associated page is in the process’s logical address space
and is thus a legal (or valid) page. When the bit is set to invalid, the page is not in the
process’s logical address space. Illegal addresses are trapped by use of the valid–invalid bit.
The operating system
Structure of the Page Table:
Hierarchical Paging:
We would not want to allocate the page table contiguously in main memory. One simple
solution to this problem is to divide the page table into smaller pieces. We can accomplish
this division in several ways. One way is to use a two-level paging algorithm
Where p1 is an index into the outer page table and p2 is the displacement within the page
of the inner page table. The address-translation method for this architecture is shown in
Figure below.
Because address translation works from the outer page table inward, this scheme is also
known as a forward-mapped page table.
129
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
An inverted page table has one entry for each real page (or frame) of memory. Each entry
consists of the virtual address of the page stored in that real memory location; with
information about the process that owns the page. Thus, only one page table is in the
system, and it has only one entry for each page of physical memory.
Software Required:
Turbo C or telnet.
Procedure:
Goto turbo C
Compile the C program by compile.
Run the C program by run.
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
Algorithm:
1. Start
2. Declare the structure P_table with variables for page no and frame no
3. Display the status of physical memory
4. Get the number of pages needed for a process
5. Get the contents of the pages
6. Display the contents of logical memory
7. If the physical memory is available then allot the pages of the process
8. Update the physical memory status
9. Update the page table status
10. Display the page table after allocation
11. Display the physical memory after allocation
12. Stop
Program:
#include<stdio.h>
#include<conio.h>
struct logical
{
char log[10];
}lg[40];
130
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
struct physical
{
char phy1[10];
}phy[40];
void main()
{
int p,phadr,nopage,disp,npgframe,spage,i,j,frameno[40],fsize,ph;
char ch='A';
//clrscr();
printf("enter the number of pages:");
scanf("%d",&nopage);
printf("\n enter the size of each page:");
scanf("%d",&spage);
printf("\nlogical address \t content");
printf("\n------------------------");
for(i=0;i<nopage;i++)
{
printf("\n%d",i);
for(j=0;j<spage;j++)
{
printf("\t\t\t");
printf("%c",ch);
lg[i].log[j]=ch;
ch++;
printf("\n");
}
printf("\n------------------------");
}
printf("\n enter the no of frames(should be<=[Link]):");
scanf("%d",&npgframe);
fsize=spage;
printf("\n enter the frame no");
printf("\n\t page table");
printf("\n--------");
printf("\n page no.\t frame number");
for(i=0;i<nopage;i++)
{
printf("\n");
printf("%d",i);
printf("\t\t\t");
131
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
scanf("%d",&frameno[i]);
}
printf("\n logical address physical address");
for(i=0;i<nopage;i++)
{
printf("\n");
printf("%d",i);
printf("\t\t\t");
p=frameno[i]*fsize;
printf("%d",p);
for(j=0;j<spage;j++)
phy[p].phy1[j]=lg[i].log[j];
}
printf("\n enter the logical address:");
scanf("%d",&ph);
printf("\n enter the displacement 0-%d:",spage-1);
scanf("%d",&disp);
phadr=(frameno[ph]*spage)+disp;
printf("\n data is :%c",lg[ph].log[disp]);
printf("\n physical address is %d",phadr);
//getch();
}
OUTPUT:
[cse01@telnet ~]$ ./[Link]
enter the number of pages:4
132
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
3 J
K
L
-------------------------------------
enter the no of frames(should be<=[Link]
enter the frame no
page table
--------
page no. frame number
0 2
1 3
2 1
3 0
133
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Every address generated by the CPU is divided into two parts: a page number (p)
and a page offset (d). The page number is used as an index into a page table. The page
table contains the base address of each page in physical memory.
Advantages:
When we use a paging scheme, we have no external fragmentation: any free frame can
be allocated to a process that needs it. However, we may have some internal fragmentation.
Notice that frames are allocated as units. If the memory requirements of a process do not
happen to coincide with page boundaries, the last frame allocated may not be completely
full.
3. What is Translation Look aside Buffer.
Small, fast lookup hardware cache called a translation look-aside buffer (TLB)
only a few of the page-table entries.
4. Explain the Structure of the Page Table.
o Hierarchical Paging
o Hashed Page Tables
o Inverted Page Tables
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
Result:-
Thus the c program for implementation of Memory allocation with pages was
executed and the output was verified successfully.
134
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
If the selected page has been modified, it must be copied back to disk (swapped out)
Theory:
FIFO Page Replacement
The simplest page-replacement algorithm is a first-in, first-out (FIFO) algorithm. A
FIFO replacement algorithm associates with each page the time when that page was
brought into memory.
In the above example reference string, three frames are initially empty. Thefirst three
references (7, 0, 1) because page faults and are brought into these empty frames. The next
reference (2) replaces page 7, because page 7 was brought in first. Since 0 is the next
reference and 0 is already in memory, we have no fault for this reference. The first
reference to 3 results in replacement of page 0, since it is now first in line. Because of this
replacement, the next reference, to 0, will fault. Page 1 is then replaced by page 0. Every
time a fault occurs, we show which pages are in our three frames. There are fifteen faults
altogether.
135
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
One result of the discovery of Belady’s anomaly was the search for an optimal page-
Replacement algorithm—the algorithm that has the lowest page-fault rate of all
algorithms and will never suffer from Belady’s anomaly. Such an algorithm does exist and
has been called OPT or MIN. It is simply this: Replace the page that will not be used for the
longest period of time. Use of this page-replacement algorithm guarantees the lowest
possible page fault rate for a fixed number of frames.
In the above example, sample reference string, the optimal page-replacement algorithm
would yield nine page faults, as shown in the Figure above. The first three references cause
faults that fill the three empty frames. The reference to page 2 replaces page 7, because
page 7 will not be used until reference 18, whereas page 0 will be used at 5, and page 1 at
14. The reference to page 3 replaces page 1, as page 1 will be the last of the three pages in
memory to be referenced again. With only nine page faults, optimal replacement is much
better than a FIFO algorithm, which results in fifteen faults. No replacement algorithm can
process this reference string in three frames with fewer than nine faults.
LRU replacement associates with each page the time of that page’s last [Link] a page
must be replaced; LRU chooses the page that has not been usedfor the longest period of
time.
136
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
LRU replacement with twelve faults is much better than FIFO replacement with fifteen.
• The least frequently used (LFU) page-replacement algorithm requires that the page
with the smallest count be replaced. The reason for this selection is that an actively used
page should have a large reference count. A problem arises, however, when a page is used
heavily during the initial phase of a process but then is never used again. Since it was used
heavily, it has a large count and remains in memory even though it is no longer needed. One
solution is to shift the counts right by 1 bit at regular intervals, forming an exponentially
decaying average usage count.
• The most frequently used (MFU) page-replacement algorithm is based on the argument
that the page with the smallest count was probably just brought in and has yet to be used.
Software Required:
Turbo C or telnet.
Procedure:
Goto turbo C
Compile the C program by compile.
Run the C program by run.
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
Aim
To write a c program to implement FIFO page replacement algorithm
Algorithm
1. Start the process
2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Forma queue to hold all pages
6. Insert the page require memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted
9. Display the values
137
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
PROGRAM:
#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
return 0;
}
138
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
OUTPUT:
ENTER THE NUMBER OF PAGES: 20
ENTER THE PAGE NUMBER : 70120304230321201701
ENTER THE NUMBER OF FRAMES :3
ref string page frames
7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
0
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
3
2
1 0 1 3
2 0 1 2
0
1
7 7 1 2
0 7 0 2
1 7 0 1
Page Fault Is 15
Result:-
Thus the c program for the implementation of FIFO page replacement algorithms
was executed and the output was verified successfully.
Aim:
To write a c program to implement LRU page replacement algorithm
139
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Algorithm:
1. Start the process
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process
Program:
Bottom of Form
#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
int index,k,l,flag1=0,flag2=0,pf=0,frsize=3;
clrscr();
for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0,flag2=0;
for(i=0;i<3;i++)
{
if(fr[i]==p[j])
{
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
140
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
{
for(i=0;i<3;i++)
{
if(fr[i]==-1)
{
fr[i]=p[j];
flag2=1;
break;
}
}
}
if(flag2==0)
{
for(i=0;i<3;i++)
fs[i]=0;
for(k=j-1,l=1;l<=frsize-1;l++,k--)
{
for(i=0;i<3;i++)
{
if(fr[i]==p[k])
fs[i]=1;
}
}
for(i=0;i<3;i++)
{
if(fs[i]==0)
index=i;
}
fr[index]=p[j];
pf++;
}
display();
}
printf("\n no of page faults :%d",pf);
getch();
}
void display()
{
int i;
printf("\n");
141
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
for(i=0;i<3;i++)
printf("\t%d",fr[i]);
}
OUTPUT :
2 -1 -1
2 3 -1
2 3 -1
2 3 1
2 5 1
2 5 1
2 5 4
2 5 4
3 5 4
3 5 2
3 5 2
3 5 2
no of page faults : 4
Result:-
Thus the c program for the implementation of LRU page replacement algorithms
was executed and the output was verified successfully.
Aim:
To write a c program to implement LFU page replacement algorithm
Algorithm:
1. Start the process
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least frequently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process
142
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Program:
#include<stdio.h>
int main()
{
int f,p;
int pages[50],frame[10],hit=0,count[50],time[50];
int i,j,page,flag,least,minTime,temp;
for(i=0;i<f;i++)
{
frame[i]=-1;
}
for(i=0;i<50;i++)
{
count[i]=0;
}
printf("Enter page no : \n");
for(i=0;i<p;i++)
{
scanf("%d",&pages[i]);
}
printf("\n");
for(i=0;i<p;i++)
{
count[pages[i]]++;
time[pages[i]]=i;
flag=1;
least=frame[0];
for(j=0;j<f;j++)
{
if(frame[j]==-1 || frame[j]==pages[i])
{
if(frame[j]!=-1)
{
143
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
hit++;
}
flag=0;
frame[j]=pages[i];
break;
}
if(count[least]>count[frame[j]])
{
least=frame[j];
}
}
if(flag)
{
minTime=50;
for(j=0;j<f;j++)
{
if(count[frame[j]]==count[least] && time[frame[j]]<minTime)
{
temp=j;
minTime=time[frame[j]];
}
}
count[frame[temp]]=0;
frame[temp]=pages[i];
}
for(j=0;j<f;j++)
{
printf("%d ",frame[j]);
}
printf("\n");
}
printf("Page hit = %d",hit);
return 0;
}
144
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output ::
145
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
Result:-
Thus the c program for the implementation of LFU page replacement algorithms
was executed and the output was verified successfully.
146
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
147
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
through all the subdirectories to a specified file. A directory (or sub directory) contains
a set of files or sub directories. A directory is simply another file. But it is treated in a
special way. All directories have the same internal format.
4. Acyclic Graph Directory.
An acyclic graph is a graph with no cycles. To implement shared files and
subdirectories this directory structure is used.
An acyclic – graph directory structure is more flexible than is a simple tree
structure, but it is also more complex. In a system where sharing is implemented by
symbolic link, this ituation is somewhat easier to handle. The deletion of a link does not
need to affect the original file; only the link is removed. Another approach to deletion is
to preserve the file until all references to it are deleted. To implement this approach, we
must have some mechanism for determining that the last reference to the file has been
deleted.
Software Required:
Turbo C or telnet.
Procedure:
Goto turbo C
Compile the C program by compile.
Run the C program by run.
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
Aim:
To implement Single level directory structure in C.
Algorithm:
1. Start
2. Declare the number, names and size of the directories and file names.
3. Get the values for the declared variables.
4. Display the files that are available in the directories.
5. Stop.
Program:
#include<stdio.h>
#include<conio.h>
148
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
main()
{
int master,s[20];
char f[20][20][20];
char d[20][20];
int i,j;
clrscr();
printf("enter number of directorios:");
scanf("%d",&master);
printf("enter names of directories:");
for(i=0;i<master;i++)
scanf("%s",&d[i]);
printf("enter size of directories:");
for(i=0;i<master;i++)
scanf("%d",&s[i]);
printf("enter the file names :");
for(i=0;i<master;i++)
for(j=0;j<s[i];j++)
scanf("%s",&f[i][j]);
printf("\n");
printf(" directory\tsize\tfilenames\n");
printf("*************************************************\n");
for(i=0;i<master;i++)
{
printf("%s\t\t%2d\t",d[i],s[i]);
for(j=0;j<s[i];j++)
printf("%s\n\t\t\t",f[i][j]);
printf("\n");
}
printf("\t\n");
getch();
}
Program:
//single level directory structure
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#define SX 150
#define SY 200
149
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
#define BL 30
#define BW 15
int n;
char a[10][10];
int cols[]={2,5,1,3,4,6,8,7,9};
void readfiles()
{
int i;
printf("\nEnter no. of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter file name:");
scanf("%s",&a[i]);
}
}
void fillspace()
{
int x1,y1,i;
outtextxy(70,205,"Directory");
outtextxy(100,255,"Files");
for(i=0;i<n;i++)
{
setfillstyle(1,cols[i]);
x1=SX+(i%10)*40;
y1=SY+(i/10)*40;
bar(x1,y1,x1+BL,y1+BW);
outtextxy(x1+BL/4,y1+BW/4,a[i]);
line(x1+BL/2,y1+BW,x1+BL/2,y1+50);
circle(x1+BL/2,y1+60,7);
}
}
void main()
{
int gm,gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
readfiles();
fillspace();
getch();
closegraph();}
150
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output:
Result:-
Thus the c program to implement the Single level directory file organization
techniques was executed and the output was verified successfully.
Aim:
To implement Two-level directory structure in C.
Algorithm:
1. Start
2. Declare the number, names and size of the directories and subdirectories and file names.
3. Get the values for the declared variables.
4. Display the files that are available in the directories and subdirectories.
5. Stop.
Program:
#include<stdio.h>
#include<conio.h>
struct st
{
151
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
char dname[10];
char sdname[10][10];
char fname[10][10][10];
int ds,sds[10];
}dir[10];
void main()
{
int i,j,k,n;
clrscr();
printf("enter number of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter directory %d names:",i+1);
scanf("%s",&dir[i].dname);
printf("enter size of directories:");
scanf("%d",&dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("enter subdirectory name and size:");
scanf("%s",&dir[i].sdname[j]);
scanf("%d",&dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
{
printf("enter file name:");
scanf("%s",&dir[i].fname[j][k]);
}
}
}
printf("\ndirname\t\tsize\tsubdirname\tsize\tfiles");
printf("\n******************************************************\n");
for(i=0;i<n;i++)
{
printf("%s\t\t%d",dir[i].dname,dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("\t%s\t\t%d\t",dir[i].sdname[j],dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
printf("%s\t",dir[i].fname[j][k]);
printf("\n\t\t");
152
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
}
printf("\n");
}
getch();
}
Program:
//two level directory structure
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#define SX 250
#define SY 200
#define BL 30
#define BW 15
#define SY1 250
int SX1=100;
int n,m[10];
char a[10][10];
int cols[]={2,5,1,3,4,6,8,7,9};
typedef struct
{
char name[10];
struct
{
char file[10];
} k[10];
}file_info;
file_info f[10];
void readfiles()
{
int i,j;
printf("\nEnter no. of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter %d directory:",i+1);
scanf("%s",&f[i].name);
printf("enter [Link] files:");
scanf("%d",&m[i]);
153
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
for(j=0;j<m[i];j++)
{
printf("enter %d file name:",j+1);
scanf("%s",&f[i].k[j].file);
}
}
}
void fillspace()
{
int x1,y1,i,j;
outtextxy(70,205,"Directory");
outtextxy(100,255,"Files");
for(i=0;i<n;i++)
{
setfillstyle(1,cols[i]);
x1=SX+(i%10)*50;
y1=SY+(i/10)*40;
bar(x1,y1,x1+BL+20,y1+BW);
outtextxy(x1+BL/4,y1+BW/4,f[i].name);
line(x1+BL/2,y1+BW,SX1+50,SY1);
SX1=SX1+50;
for(j=0;j<m[i];j++)
{ setfillstyle(1,cols[i]);
x1=SX1+(j%10)*40;
y1=SY1+(j/10)*40;
bar(x1,y1,x1+BL+10,y1+BW);
outtextxy(x1+BL/4,y1+BW/4,f[i].k[j].file);
line(x1+BL/2,y1+BW,x1+BL/2,y1+50);
circle(x1+BL/2,y1+60,7);
}
SX1=SX1+100;
}
}
void main()
{
int gm,gd=DETECT;
initgraph(&gd,&gm,"c:\\tc\\bgi");
readfiles();
cleardevice();
getch();
154
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
fillspace();
getch();
closegraph();
}
Output:
Enter name of dir/file(under root):ROOT
Enter 1 for Dir/2 for file:1
No of sub directories/files(for ROOT):2
Enter name of dir/file(under ROOT):USER 1
Enter 1 for Dir/2 for file:1
No of sub directories/files(for USER 1):1
Enter name of dir/file(under USER 1):SUBDIR
Enter 1 for Dir/2 for file:1
No of sub directories/files(for SUBDIR):1
Enter name of dir/file(under SUBDIR):USER2
Enter 1 for Dir/2 for file:1
No of sub directories/files(for USER2):1
Enter name of dir/file(under USER2):USER3
Enter 1 for Dir/2 for file:1
Result:-
Thus the c program to implement the two-level directory file organization
techniques was executed and the output was verified successfully.
Aim:
To implement hierarchical directory structure in C.
Algorithm:
1. Start
2. Declare the number, names and size of the directories and subdirectories and file names.
3. Get the values for the declared variables.
4. Display the files that are available in the directories and subdirectories.
5. Stop.
155
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Program:
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create (&root,0,”root”,0,639,320);
clrscr();
initgraph(&gd,&gm,”c:\\tc\\BGI”);
display(root);
getch();
closegraph();
}
create (node **root,int lev,char *dname,int [Link] rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf(“Enter name of dir/file(under %s):”,dname);fflush(stdin);
gets((*root)->name);
printf(“enter 1 for dir/2 for fie:”);
scanf(“%d”,&(*root)->ftype);
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
156
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
if((*root)->ftype==1)
{
printf(“No of subdirectories/files(for %s):”,(*root)->name);
scanf(“%d”,&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create (&((*root)->link[i]),lev+1,(*root)-
>name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else (*root)->nc=0;
}
}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
Display(root->link[i]);
}
}
}
157
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Output:
Enter name of dir/file(under root):ROOT
Enter 1 for Dir/2 for file:1
No of sub directories/files(for ROOT):2
Enter name of dir/file(under ROOT):USER 1
Enter 1 for Dir/2 for file:1
No of sub directories/files(for USER 1):1
Enter name of dir/file(under USER 1):SUBDIR
Enter 1 for Dir/2 for file:1
No of sub directories/files(for SUBDIR):2
Enter name of dir/file(under USER 1):JAVA
Enter 1 for Dir/2 for file:1
No of sub directories/files(for JAVA):0
Enter name of dir/file(under SUBDIR):VB
Enter 1 for Dir/2 for file:1
No of sub directories/files(for VB):0
Enter name of dir/file(under ROOT):USER2
Enter 1 for Dir/2 for file:1
No of sub directories/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):SUBDIR2
Enter 1 for Dir/2 for file:1
No of sub directories/files(for SUBDIR2):2
Enter name of dir/file(under SUBDIR2):PPL
Enter 1 for Dir/2 for file:1
No of sub directories/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 sub directories/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
Enter 1 for Dir/2 for file:2
158
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Result:-
Thus the c program to implement the Hierarchical directory file organization
techniques was executed and the output was verified successfully
14.d. Directed Acyclic Graph (DAG)
Aim:
To implement Directed Acyclic Graph in C.
Algorithm:
1. Start
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.
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<string.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
typedef struct
{
char from[20];
char to[20];
}link;
link L[10];
int nofl;
node *root;
void main()
{
int gd=DETECT,gm;
root=NULL;
clrscr();
159
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
create (&root,0,”root”,0,639,320);
read_links();
clrscr();
initgraph(&gd,&gm,”c:\\tc\\BGI”);
draw_link_lines();
display(root);
getch();
closegraph();
}
read_links()
{
int i;
printf(“How many links:”);
scanf(“%d”,&nofl);
for(i=0;i<nofl;i++)
{
printf(“File/dir:”);
fflush(stdin);
gets(L[i].from);
printf(“User name:”);
fflush(stdin);
gets(L[i].to);
}
}
draw_link_lines()
{
int i,x1,y1,x2,y2;
for(i=0;i<nofl;i++)
{
search(root,L[i].from,&x1,&y1);
search(root,L[i].to,&x2,&y2);
setcolor(LIGHTGREEN);
setlinestyle(3,0,1);
line(x1,y1,x2,y2);
setcolor(YELLOW);
setlinestyle(0,0,1);
}
}
search(node *root,char *s,int *x,int *y)
{
160
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
int i;
if(root!=NULL)
{
if(strcmpi(root->name,s)==0)
{
*x=root->x;
*y=roor->y;
return;
}
else
{
for(i=0;i<root->nc;i++)
search(root->link[i],s,x,y);
}
}
}
create (node **root,int lev,char *dname,int [Link] rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf(“Enter name of dir/file(under %s):”,dname);fflush(stdin);
gets((*root)->name);
printf(“enter 1 for dir/2 for fie:”);
scanf(“%d”,&(*root)->ftype);
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf(“No of subdirectories/files(for %s):”,(*root)->name);
scanf(“%d”,&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else
161
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create (&((*root)->link[i]),lev+1,(*root)-
>name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else (*root)->nc=0;
}
}
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
Display(root->link[i]);
}
}
}
Output:
Enter name of dir/file(under root):ROOT
Enter 1 for Dir/2 for file:1
No of sub directories/files(for ROOT):2
Enter name of dir/file(under ROOT):USER 1
Enter 1 for Dir/2 for file:1
No of sub directories/files(for USER 1):1
Enter name of dir/file(under SUBDIR):VB
162
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
163
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
In the two level directory structures, each user has her own user file directory
(UFD). When a user job starts or a user logs in, the system‘s master file directory (MFD)
is searched. The MFD is indexed by user name or account number, and each entry
points to the UFD for that user.
4. Define Tree – Structured Directory.
A tree is the most common directory structure. The tree has a root directory. Every
file in the system has a unique path name. A path name is the path from the root,
through all the subdirectories to a specified file. A directory (or sub directory) contains
a set of files or sub directories. A directory is simply another file. But it is treated in a
special way. All directories have the same internal [Link] bit in each directory
entry defines the entry as a file (0) or as a subdirectory (1).
5. What is Acyclic Graph Directory?
An acyclic graph is a graph with no cycles. To implement shared files and
subdirectories this directory structure is used. An acyclic – graph directory structure is
more flexible than is a simple tree structure, but it is also more complex. In a system
where sharing is implemented by symbolic link, this ituation is somewhat easier to
handle. The deletion of a link does not need to affect the original file; only the link is
removed. Another approach to deletion is to preserve the file until all references to it
are deleted.
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
Result:-
Thus the c program to implement the Directed Acyclic graph file organization
techniques was executed and the output was verified successfully.
164
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Linked Allocation
165
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Linked allocation solves all problems of contiguous allocation. With linked allocation,
each file is a linked list of disk blocks; the disk blocks may be scattered anywhere on the
disk. The directory contains a pointer to the first and last blocks of the file. For example, a
file of five blocks might start at block 9 and continue at block 16, then block 1, then block
10, and finally block 25 each block contains a pointer to the next block. These pointers are
not made available to the user. Thus, if each block is 512 bytes in size, and a disk address
(the pointer) requires 4 bytes, then the user sees blocks of 508 bytes.
Indexed Allocation
Linked allocation solves the external-fragmentation and size-declaration problems
of contiguous allocation. However, in the absence of a FAT, linked allocation cannot
support efficient direct access, since the pointers to the blocks are scattered with the
blocks themselves all over the disk and must be retrieved in order. Indexed allocation
solves this problem by bringing all the pointers together into one location: the index
block.
Each file has its own index block, which is an array of disk-block [Link]
ithentry in the index block points to the ithblock of the file. The directory block, we use
the pointer in the ithindex-block entry.
.
Software Required:
Turbo C or telnet.
166
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Procedure:
Goto turbo C
Compile the C program by “compile”.
Run the C program by “run”.
(or)
Goto Command promand by typing run->telenet [Link]
Log in with their username and password.
Start typing vi filename.c
Compile cc filename.c
Run ./[Link]
Aim:
To implement Sequential file allocation in C.
Algorithm:
1. Start
2. Declare the starting block no. and the length of the file.
3. Get the Starting block no. and length of the file from the user.
4. Allocate files sequentially until end of the file.
5. Display the fragments of the file.
6. Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int f[50],i,st,j,len,c,k;
clrscr();
for(i=0;i<50;i++)
f[i]=0;
X:
printf("\n Enter the starting block & length of file");
scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++)
if(f[j]==0)
{
f[j]=1;
167
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
printf("\n%d->%d",j,f[j]);
}
else
{
printf("Block already allocated");
break;
}
if(j==(st+len))
printf("\n the file is allocated to disk");
printf("\n if u want to enter more files?(y-1/n-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
exit();
getch();
}
Output:
Result:-
Thus the c program for the implementation of Sequential file Allocation Strategies
was executed and the output was verified successfully.
168
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int f[50],i,k,j,inde[50],n,c,count=0,p;
clrscr();
for(i=0;i<50;i++)
f[i]=0;
x:
printf("enter index block\t");
scanf("%d",&p);
if(f[p]==0)
{
f[p]=1;
printf("enter no of files on index\t");
scanf("%d",&n);
}
else
{
printf("Block already allocated\n");
goto x;
}
for(i=0;i<n;i++)
scanf("%d",&inde[i]);
for(i=0;i<n;i++)
169
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
if(f[inde[i]]==1)
{
printf("Block already allocated");
goto x;
}
for(j=0;j<n;j++)
f[inde[j]]=1;
printf("\n allocated");
printf("\n file indexed");
for(k=0;k<n;k++)
printf("\n %d->%d:%d",p,inde[k],f[inde[k]]);
printf(" Enter 1 to enter more files and 0 to exit\t");
scanf("%d",&c);
if(c==1)
goto x;
else
exit();
getch();
}
Output:
Result:- Thus the c program for the implementation of Indexed file Allocation
Strategies was executed and the output was verified successfully.
4.c. Linked File Allocation
170
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Aim:
To allocate the files in the secondary storage using Linked allocation technique
Algorithm:
1. Start
2. Initialize the AVAIL linked list, where each node consist of starting address, size of the
empty
block and a link for next available node
3. Initialialize the FAT ( File Allocation Table) which is implemented as array of pointers.
4. Display the AVAIL List
5. Read File allocation request which consist of File name, No of blocks and its contents
6. Traverse the AVAIL linked list from the starting node
7. Retrieve the required no of blocks from AVAIL List
8. Assign the contents of file to the retrieved blocks
9. Update the FAT by making an entry in FAT
10. Update the AVAIL LIST
11. Display the AVAIL List and FAT table
12. Stop
Program:
#include<stdio.h>
#include<conio.h>
main()
{
int f[50],p,i,j,k,a,st,len,n,c;
clrscr();
for(i=0;i<50;i++)
f[i]=0;
printf("Enter how many blocks that are already allocated");
scanf("%d",&p);
printf("\nEnter the blocks no.s that are already allocated");
for(i=0;i<p;i++)
{
scanf("%d",&a);
f[a]=1;
}
X:
printf("Enter the starting index block & length");
scanf("%d%d",&st,&len);
k=len;
171
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n %d->file is already allocated",j);
k++;
}
}
printf("\n If u want to enter one more file? (yes-1/no-0)");
scanf("%d",&c);
if(c==1)
goto X;
else
exit();
getch( );
}
Output:
172
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
block of the file. The directory block, we use the pointer in the index-block entry.
References:
Abraham Silberschatz, Peter Baer Galvin and Greg Gagne, “Operating System Concepts”, 9 th
Edition, John Wiley and Sons Inc., 2012.
173
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB
Result:- Thus the c program for the implementation of Linked file Allocation
Strategies was executed and the output was verified successfully.
174