0% found this document useful (0 votes)
363 views180 pages

OS Lab Manual

Operating Systems

Uploaded by

anithaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Topics covered

  • Synchronization,
  • File Organization,
  • Indexed Allocation,
  • Laboratory Manual,
  • CPU Scheduling,
  • File Allocation Strategies,
  • Unix Commands,
  • Linked Allocation,
  • Memory Management,
  • Threading
0% found this document useful (0 votes)
363 views180 pages

OS Lab Manual

Operating Systems

Uploaded by

anithaa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Topics covered

  • Synchronization,
  • File Organization,
  • Indexed Allocation,
  • Laboratory Manual,
  • CPU Scheduling,
  • File Allocation Strategies,
  • Unix Commands,
  • Linked Allocation,
  • Memory Management,
  • Threading

FRANCIS XAVIER ENGINEERING COLLEGE

TIRUNELVELI

DEPARTMENT OF COMPUTER SCIENCE &


ENGINEERING

LAB MANUAL
CS8461 OPERATING SYSTEMS
LABORATORY

Prepared by Verified by Approved by

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

1. Basics of UNIX commands


2. Write programs using the following system calls of UNIX operating system
fork, exec, getpid, exit, wait, close, stat, opendir, readdir
3. Write C programs to simulate UNIX commands like cp, ls, grep, etc.
4. Shell Programming
5. Write C programs to implement the various CPU Scheduling Algorithms
6. Implementation of Semaphores
7. Implementation of Shared memory and IPC
8. Bankers Algorithm for Deadlock Avoidance
9. Implementation of Deadlock Detection Algorithm
10. Write C program to implement Threading & Synchronization Applications
11. Implementation of the following Memory Allocation Methods for fixed partition
a) First Fit b) Worst Fit c) Best Fit
12. Implementation of Paging Technique of Memory Management
13. Implementation of the following Page Replacement Algorithms
a) FIFO b) LRU c) LFU
14. Implementation of the various File Organization Techniques
15. Implementation of the following File Allocation Strategies
a) Sequential b) Indexed c) Linked
TOTAL: 60 PERIODS

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

The Objectives of this lab course are


 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

Course 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
 Analyze the performance of the various Page Replacement Algorithms
 Implement File Organization and File Allocation Strategies

Mapping of PO with CO

iii
Implement Deadlock avoidance

Analyze the performance of the


and
Course Outcomes

and File Allocation Strategies


Compare the performance of

Implement File Organization


various Page Replacement
Implement Semaphores
various CPU Scheduling

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.

POb Problem Analysis: Identify and solve


engineering problems reaching conclusions L L L
using mathematics and engineering sciences. H

POc Design/Development of Solutions:


Design and develop solutions for engineering L L M L L
problems that meet specified needs.

POd Conduct Investigations of Complex


Problems: Conduct investigations of L L L L
complex problems including design of M
experiments and analysis to provide valid
solutions.

POe Modern Tool Usage: Create and apply


appropriate techniques, resources, and L L
H
modern engineering tools for executing
engineering activities.

POf The Engineer and Society: Apply


reasoning of the societal, safety issues and L
L
the consequent responsibilities relevant to
engineering practice.

POg Environment and Sustainability:


Understand the impact of engineering L L
solutions in the environment and exhibit the
knowledge for sustainable development.

iv
Implement Deadlock avoidance

Analyze the performance of the


and
Course Outcomes

and File Allocation Strategies


Compare the performance of

Implement File Organization


various Page Replacement
Implement Semaphores
various CPU Scheduling

processes
implement IPC
Program

Algorithms

Algorithms
Outcomes

Create
POh Ethics: Apply ethical principles and
commit to professional ethics,
responsibilities and norms of engineering
practice.

POi Individual and Team Work: Function


effectively as an individual, and as a member L M
or leader in diverse teams in multi-
disciplinary settings.

POj Communication: Communicate


effectively to the engineering community and
the outside world and also to write effective L
reports.

POk Project Management and Finance:


Understand engineering and management M M H M
principles and apply them to handle projects
in multi disciplinary environments.

POl Life-Long Learning: Recognize the


need for life-long learning and apply in the L L L L
context of technological change.

v
[Link] No of
Name of the Exercise
Hours
1 LIST OF EXPERIMENTS
Basics of UNIX commands 6

2 Write programs using the following system calls of UNIX operating 6


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

3 Write C programs to simulate UNIX commands like cp, ls, grep, etc 3

4 Shell Programming 3

Write C programs to implement the various CPU Scheduling


5 6
Algorithms

6 Implementation of Semaphores 3

7 Implementation of Shared memory and IPC 3

8 Bankers Algorithm for Deadlock Avoidance 3

9 Implementation of Deadlock Detection Algorithm 3

Write C program to implement Threading & Synchronization 3


10
Applications
Implementation of the following Memory Allocation Methods for
11 fixed partition 6
a) First Fit b) Worst Fit c) Best Fit

12 Implementation of Paging Technique of Memory Management 3

Implementation of the following Page Replacement Algorithms


13 6
a) FIFO b) LRU c) LFU

14 Implementation of the various File Organization Techniques 3

Implementation of the following File Allocation Strategies


15 a) Sequential b) Indexed c) Linked 3

Total Hours: 60

vi
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

Ex No: 1 BASIC UNIX COMMANDS

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.

Command Example Description

1. ls ls Lists files in current directory


ls -alF List in long format

2. cd cd tempdir Change directory to tempdir

1
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

cd .. Move back one directory


cd ~dhyatt/web-docs Move into dhyatt's web-docs directory

3. mkdir mkdir graphics Make a directory called graphics

4. rmdir rmdir emptydir Remove directory (must be empty)

5. cp cp file1 web-docs Copy file into directory


cp file1 [Link] Make backup of file1

6. rm rm [Link] Remove or delete file


rm *.tmp Remove all file

7. mv mv [Link] [Link] Move or rename files

8. more more [Link] Look at file, one page at a time

9. lpr lpr [Link] Send file to printer

10. man man ls Online manual (help) about command

Ten VALUABLE UNIX Commands


Once you have mastered the basic UNIX commands, these will be quite valuable in managing your
own account.

Command Example Description

1. grep grep "bad word" * Find which files contain a


<str><files> certain word

2
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

2. chmod <opt> chmod 644 *.html Change file permissions read


<file> chmod 755 [Link] only
Change file permissions to
executable

3. passwd passwd Change passwd

4. ps <opt> ps aux List all running processes by


ps aux | grep dhyatt #ID
List process #ID's running by
dhyatt

5. kill <opt> <ID> kill -9 8453 Kill process with ID #8453

6. gcc (g++) gcc file.c -o file Compile a program written


<source> g++ [Link] -o fil2 in C
Compile a program written
in C++

7. gzip <file> gzip bigfile Compress file


gunzip [Link] Uncompress file

8. mail mail me@[Link] < Send file1 by email to


(pine) file1 someone
pine Read mail using pine

9. telnet <host> telnet Open a connection to vortex


ssh <host> [Link] Open a secure connection to
ssh -l dhyatt jazz as user dhyatt
[Link]

10. ftp <host> ftp [Link] Upload or Download files to


ncftp station1

3
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

<host/directory> ncftp [Link] Connect to archives at UNC

Ten FUN UNIX Commands


These are ten commands that you might find interesting or amusing. They are actually quite helpful at
times, and should not be considered idle entertainment.

Command Example Description

1. who who Lists who is logged on your machine

2. finger finger Lists who is on computers in the lab

3. ytalk ytalk Talk online with dhyatt who is on


<user@place> dhyatt@threat threat

4. history history Lists commands you've done


recently

5. fortune fortune Print random humerous message

6. date date Print out current date

7. cal <mo> cal 9 2000 Print calendar for September 2000


<yr>

8. xeyes xeyes & Keep track of cursor (in


"background")

9. xcalc xcalc & Calculator ("background" process)

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!)

Ten HELPFUL UNIX Commands


These ten commands are very helpful, especially with graphics and word processing type applications.

Command Example Description

1. netscape netscape & Run Netscape browser

2. xv xv & Run graphics file converter

3. xfig / xpaint xfig & (xpaint Run drawing program


&)

4. gimp gimp & Run photoshop type program

5. ispell <fname> ispell file1 Spell check file1

6. latex <fname> latex [Link] Run LaTeX, a scientific


document tool

7. xemacs / pico xemacs (or Different editors


pico)

8. soffice soffice & Run StarOffice, a full word


processor

5
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

9. m-tools (mdir, mdir a: DOS commands from UNIX (dir


mcopy, mcopy file1 a: A:)
mdel, mformat, etc. Copy file1 to A:
)

10. gnuplot gnuplot Plot data graphically

Ten USEFUL UNIX Commands:


These ten commands are useful for monitoring system access, or s implifying your own
environment.

Command Example Description

1. df df See how much free disk space

2. du du -b subdir Estimate disk usage of directory in


Bytes

3. alias alias lls="ls -alF" Create new command "lls" for long
format of ls

4. xhost xhost + Permit window to display from x-


[Link] window program from threat
xhost - Allow no x-window access from
other systems

5. fold fold -s file1 | lpr Fold or break long lines at 60


characters and send to printer

6
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

6. tar tar -cf [Link] Create an archive called [Link]


subdir of a directory
tar -xvf [Link] Extract files from an archive file

7. ghostview gv [Link] View a Postscript file


(gv)

8. ping ping [Link] See if machine is alive


(traceroute) traceroute Print data path to a machine
[Link]

9. top top Print system usage and top


resource hogs

10. logout logout or exit How to quit a UNIX shell.


(exit)

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

E.g. $ cat > myfile

Output
[cse01@telnet ~]$ cat > display_file
cse01
Good Girl
Study well

7
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

Eat well
Sleep well

[1]+ Stopped cat >display_file

2. Display the contents of a file


Syntax: $ cat filename
To display the contents of the file
E.g., $ cat myfile

Output
[cse01@telnet ~]$ cat display_file
cse01
Good Girl
Study well
Eat well
Sleep well

3. Append contents into a file


Syntax: $ cat>> filename
The form >> appends standard Output to an existing file.

E.g., $ cat>> filename

Output
[cse01@telnet ~]$ cat >> display_file
Thus cse01 can be crowned the best

[2]+ Stopped cat >>display_file

[cse01@telnet ~]$ cat display_file


cse01
Good Girl
Study well
Eat well
Sleep well
Thus mtec11 can be crowned the best

4. Concatenation of files (cat)


Syntax: $ cat file1 file2… >> file

8
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

It’s used to concatenate file1, file2… to file


E.g., $ cat myfile1 myfile2>>myfile3

Output

[cse01@telnet ~]$ cat > new_file


This a new file created to demonstrate concatenation of files

[3]+ Stopped cat >new_file

[cse01@telnet ~]$ cat display_file new_file >> concatenated_file


[cse01@telnet ~]$ cat concatenated_file
cse01
Good Girl
Study well
Eat well
Sleep well
Thus mtec11 can be crowned the best
This a new file created to demonstrate concatenation of files

5. Copying Files (cp)


Syntax: $ cp file1 file2
The cp command makes a copy of file1 in the current working directory and
calls it file2 or if the file2 already exists then the contents in file2 is overwritten by contents
in file1 without any warning.
E.g., $ cp myfile1 myfile2

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

6. Moving files (mv)


Syntax: $ mv file1 file2

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

[cse01@telnet ~]$ mv copied_file moved_file

[cse01@telnet ~]$ cat moved_file


cse01
Good Girl
Study well
Eat well
Sleep well
Thus mtec11 can be crowned the best
This a new file created to demonstrate concatenation of files

[cse01@telnet ~]$ cat copied_file


cat: copied_file: No such file or directory
7. Removing a file (rm)
Syntax: $ rm filename
It’s used to delete (remove) a file.
E.g., $ rm myfile1

Output

[cse01@telnet ~]$ rm moved_file

[cse01@telnet ~]$ cat moved_file


cat: moved_file: No such file or directory

8. Creating a directory (mkdir)


Syntax: mkdir directoryname
It’s used to create an empty directory
E.g,: mkdir mydir

Output
[cse01@telnet ~]$ mkdir exjayan

10
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

[cse01@telnet ~]$ cd exjayan


[cse01@telnet exjayan]$

9. Removing a directory (rmdir)


Syntax: $ rm filename
It’s used to delete (remove) a directory.
E.g.,: $ rm myfilename

Output
[cse01@telnet exjayan]$ cd
[cse01@telnet ~]$ rmdir exjayan
[cse01@telnet ~]$ cd exjayan
-bash: cd: exjayan: No such file or directory

10. Printing Current Working directory (pwd)


Syntax: $ pwd
It’s used to print the current working directory.
E.g.,: $ pwd

Output

[cse01@telnet ~]$ pwd


/home/mtec11

11. Changing to a different directory


Syntax: $ cd dirname
It’s used change the current working directory to 'another directory'.
E.g.,: $ cd mydirname

Output
[cse01@telnet ~]$ cd ex
[cse011@telnet ex]$

12. Returning to home directory


Syntax: $ cd..
The cd.. Command is used to return to home directory.
E.g.,: $ cd..

Output

11
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

[cse01@telnet ~]$ cd ex
[cse01@telnet ex]$

13. Exiting current directory


Syntax: $ cd
The cd command with no argument is used to exit from current directory.
E.g.,$ cd

Output
[cse01@telnet ex]$ cd
[cse01telnet ~]$

14. Listing files and directory


Syntax: $ ls
The ls command lists the contents (files and directories) of current working
directory in alphabetical order.
E.g.,: $ ls
Output
[cse01@telnet ~]$ ls
alpha_numbers ignisha Read_File
[Link] Input_File Reverse_file.c
Arithmetic_Manipulation Largest_Three Reverse_File.c
Arithmetic_Operations lynx_bookmarks.html salary
Biggest_Two matrix Salary
concatenated_file newcountries Sort
Count_Characters.c new_file sortcountries
Count_Characters_File.c newsortcountries String_Comparison
countries nish Student
countries_sort nisha Student1
Display_20Lines.c numbers Sum_Even_Numbers
display_file Output_File Sum_N_Natural_Numbers
Display_File_Contents.c Palindrome1.c Transpose_Matrix.c
greetings Palindrome.c unix_file
hello Palindrome_Checking.c ex

15. Listing Hidden files:


Syntax: $ ls -a
It’s used to list all files in home directory including those whose names begin with a
dot.
E.g.,: $ ls -a

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

16. Listing files and directories based on modification time


Syntax: $ls -t
It’s used to list the files and directories in the current working directory by sorting
based on modification time.

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

17. Word count (wc)


Syntax: $wc filename
The wc command is used to count number of lines/words/characters in a file.
E.g., $wc myfilename

Output
[cse01@telnet ~]$ wc new_file
1 10 62 new_file

18. Counting no of lines in a file:


Syntax: $ wc -l filename
It’s used to count the number of lines in a file.
Eg., $ wc -l myfilename

Output
[cse01@telnet ~]$ wc -l new_file
1 new_file

19. Counting no of words in a file:


Syntax: $ wc -w filename

14
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

It’s used to count the number of words in a file.


E.g., $ wc -w myfilename
Output
[cse01@telnet ~]$ wc -w new_file
10 new_file

20. Counting no of characters in a file:


Syntax: $ wc -c filename
It’s used to count the number of characters in a file.
E.g., $ wc -c myfilename

Output
[cse01@telnet ~]$ wc -c new_file
62 new_file

21. Displaying the type of a file (file)


Syntax: $file filename
The file command is used to display the type of the file.
E.g., $file myfilename

Output
[cse01@telnet ~]$ file new_file
new_file: ASCII text

22. Directing Output to a file:


Syntax: $ ls > file1
The Output of the command ls is directed to or stored in file1.
E.g., $ ls > file1

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

[cse01@telnet ~]$ echo $PATH


/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/mtec11/bin

24. Clearing the screen:


Syntax: $ tput clear / clear
It’s used to clear the terminal screen.
E.g., $ tput clear / clear

Output

The display screen was cleared


Result:
Thus the basic UNIX commands were executed and the Output was verified.

GENERAL PURPOSE COMMANDS

Aim:
To execute the general purpose commands in UNIX.

[Link] Date Command

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.

$ date +%m Displays the month


$ date +%h Displays the first three characters of the month name
$ date +%d Displays the date only
$ date +%y Displays the last two digits of the year

Date Command - Output

[cse01@telnet ~]$ date


Thu Jan 29 [Link] IST 2009
[cse01@telnet ~]$ date +%m
01
[cse01@telnet ~]$ date +%h
Jan
[cse01@telnet ~]$ date +%d
29
[cse01@telnet ~]$ date +%y
09

[Link] Echo Command


The echo command is used to print the message on the screen whatever is typed.
Syntax
$ echo text

E.g.,
$ echo learning unix is fun
learning unix is fun
Echo command-Output

17
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

[cse01@telnet ~]$ echo learning unix is fun


learning unix is fun

[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

[cse01@telnet ~]$ cal 3 2009


March 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

[cse01@telnet ~]$ cal 2009

2009

January February March


Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 1 2 3 4 5 6 7 1 2 3 4 5 6 7
4 5 6 7 8 9 10 8 9 10 11 12 13 14 8 9 10 11 12 13 14
11 12 13 14 15 16 17 15 16 17 18 19 20 21 15 16 17 18 19 20 21

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

April May June


Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 1 2 1 2 3 4 5 6
5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13
12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20
19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27
26 27 28 29 30 24 25 26 27 28 29 30 28 29 30
31
July August September
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 1 1 2 3 4 5
5 6 7 8 9 10 11 2 3 4 5 6 7 8 6 7 8 9 10 11 12
12 13 14 15 16 17 18 9 10 11 12 13 14 15 13 14 15 16 17 18 19
19 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26
26 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30
30 31
October November December
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 1 2 3 4 5 6 7 1 2 3 4 5
4 5 6 7 8 9 10 8 9 10 11 12 13 14 6 7 8 9 10 11 12
11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19
18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26
25 26 27 28 29 30 31 29 30 27 28 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

Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.


This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.

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

cse01 pts/10 Jan 29 14:25 ([Link])


mech30 pts/4 Jan 29 14:27 ([Link])

who command-Output

[cse01@telnet ~]$ who


root tty1 Jan 29 10:26
cse01 pts/10 Jan 29 14:25 ([Link])
cseb24 pts/17 Jan 29 14:53 ([Link])
cseb25 pts/16 Jan 29 14:53 ([Link])

[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

cse01 pts/10 Jan 29 14:25 ([Link])

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

[cse01@telnet ~]$ who am i


cse01 pts/10 Jan 29 14:25 ([Link])
[cse01@telnet ~]$ who -b
system boot Jan 29 09:25
[cse01@telnet ~]$ who -m
cse01 pts/10 Jan 29 14:25 ([Link])
[cse01@telnet ~]$ who -q
root cseb22 cseb31 cseb33 cseb21 cseb38 cseb36 mtec11 cseb39 cseb35 monica cseb
32 cseb22 cseb26 cseb29 cseb30 cseb23 cseb37 cseb28 cseb24 cseb30 cseb27
# users=22

[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])

finger command – Output


[cse01@telnet ~]$ finger monica
Login: monica Name: monica esther
Directory: /home/monica Shell: /bin/bash
On since Thu Jan 29 14:27 (IST) on pts/4 from [Link]
8 minutes 6 seconds idle

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

[cse01@telnet ~]$ who;date

murugan pts/10 Jan 29 14:25 ([Link])


muthu pts/4 Jan 29 14:27 ([Link])
Thu Jan 29 [Link] IST 2009

[cse01@telnet ~]$ date;who

Thu Jan 29 [Link] IST 2009


murugan pts/10 Jan 29 14:25 ([Link])
muthu pts/4 Jan 29 14:27 ([Link])

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

muthu pts/4 Jan 29 14:27 ([Link])


Thu Jan 29 [Link] IST 2009

&& 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

[cse01@telnet ~]$ date && who


Thu Jan 29 [Link] IST 2009
cse01 pts/10 Jan 29 14:25 ([Link])
monica pts/4 Jan 29 14:27 ([Link])

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.

[cse01@telnet ~]$ head 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 known.

[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

grep command – Output

[cse01@telnet ~]$ cat > countries


India Asia
USA America
China Asia
Srilanka Asia
Canada Asia

[cse01@telnet ~]$ grep Asia countries


India Asia
China Asia
Srilanka Asia
Canada Asia

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

[cse01@telnet ~]$ sort countries


Bangladesh
Burma
Canada
China
India
Srilanka
Uganda
Uruguay

[cse01@telnet ~]$ sort -r countries


Uruguay
Uganda
Srilanka
India
China
Canada
Burma
Bangladesh

[cse01@telnet ~]$ sort -c countries


sort: countries:3: disorder: China
[cse01@telnet ~]$ cat countries
India

27
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

Srilanka
China
Burma
Bangladesh
Uruguay
Uganda
Canada

[cse01@telnet ~]$ cat newcountries


Japan
Germany
Italy

[cse01@telnet ~]$ sort countries >> sortcountries


[cse01@telnet ~]$ cat sortcountries
Bangladesh
Burma
Canada
China
India
Srilanka
Uganda
Uruguay

[cse01@telnet ~]$ sort newcountries >> newsortcountries


[cse01@telnet ~]$ cat newsortcountries
Germany
Italy
Japan

[cse01@telnet ~]$ sort -m sortcountries newsortcountries


Bangladesh
Burma
Canada
China
Germany
India
Italy
Japan
Srilanka

28
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

Uganda
Uruguay
[cse01@telnet ~]$ cat >> numbers
87
81
12
45
32
10

[3]+ Stopped cat >>numbers


[cse01@telnet ~]$ sort -n numbers
10
12
32
45
81
87
[cse01@telnet ~]$ cat > alpha_numbers
12
13
21
Asia
Antartica
Babu

[3]+ Stopped cat >alpha_numbers


[cse01@telnet ~]$ sort -d alpha_numbers
12
13
21
Antartica
Asia
Babu

[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

[cse01@telnet ~]$ cut -c1 salary


P
P
S
S
B
B

[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

VIVA VOCE QUESTIONS


1. List any five basic UNIX commands.
cat—for creating a new file.
cp—for copying from file 1 to file 2.
mv—for moving the file1 to file 2.
rm—for removing or deleting the file.
ls—for listing the files and directories.
2. What is the purpose of echo command?
It is used to print the message on the screen whatever is typed.
3. What is the purpose of bc command?
Used for carrying out arithmetic manipulations.
4. What is the purpose of who command?
This command is used to know the user, who is currently logged into the system.
5. What is the purpose of (;) in UNIX command?
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.
6. What are the various filter commands in UNIX?
Head filter - head filename - used to display the first ten lines of the file.
Tail filter - tail filename - used to display 10 lines of a file from the end of a file.
7. What is the purpose of grep command?
This command is used to search and print specified patterns from a file.

Reference:
[Link]

Result
Thus the filter commands were executed and the Output was verified.

33
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

[Link]: 2 IMPLEMENTATION OF FORK, EXEC, GETPID, EXIT, WAIT, CLOSE,


STAT, OPENDIR, READDIR SYSTEM CALLS
Objective:
 To learn concept of system calls

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]

THE CHILD PROCESS ID IS 8640


THE PARENT PROCESS ID IS 8644

Implementation of execlp system call


Program:
#include<unistd.h>
#include<stdio.h>
int main(int argc,char *arg[])
{
int pid;
pid=fork();
if(pid<0)
{
printf("Error");
exit(-1);
}
else if(pid==0)
{
execlp("/bin/ls","ls",NULL);

35
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

}
else
wait(NULL);
printf("Parent Complete");
printf("Child Complete");
exit(0);
}

Output :

[cse01@telnet ~]$ cc second.c


[cse01@telnet ~]$ ./[Link]
[Link] doss hameed jeg.c nas.c sai shyam steve ven
avudai dx hanu jijo nawas.c second.c sivanambi sub vignesh
balu fiest.c hari kumar.c raj selvi sj sudhin
cj first.c j lotus ram.c sem sj.c tata
d1 gen jegan maalu rowdy shahir stephen thiya
Parent CompleteChild Complete

Implementation of wait system call


Program:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#define MAXCOUNT 5
#define BUF_SIZE 100
void ChildProcess(char [],char []);

int main()
{
pid_t pid1,pid2,pid;
int status;
int i;
char buf[BUF_SIZE];

printf("*** Parent is about to fork process ***\n");


if((pid1 = fork())<0){
printf("Failed to fork process1 \n");
exit(1);
}
else if(pid1==0)
ChildProcess("first"," ");

printf("***Parent is about to fork process 2***\n");


if((pid2 = fork())<0){

36
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

printf("Failed to fork process2\n");


exit(1);
}
else if(pid2==0)
ChildProcess("second"," ");
sprintf(buf,"***Parent enters waiting status...\n");
write(1,buf,strlen(buf));
pid = wait(&status);
sprintf(buf,"***Parent detects Process%d was done***\n",pid);
write(1,buf,strlen(buf));
pid = wait(&status);
printf("***Parent detects process%d is done***\n",pid);
printf("***Parent exists***\n");
exit(0);
return 0;
}
void ChildProcess(char *number,char *space)
{
pid_t pid;
int i;
char buf[BUF_SIZE];
pid=getpid();
sprintf(buf,"%s%sChild process starts (pid - %d)\n",space,number,pid);
write(1,buf,strlen(buf));
for(i=1;i<=MAXCOUNT;i++){
sprintf(buf,"%s%s child's Output,value - %d)\n",space,number,i);
write(1,buf,strlen(buf));
}
sprintf(buf,"%s%schild(pid - %d)is about to exit\n",
space,number,pid);
write(1,buf,strlen(buf));
exit(0);
}

Output :

[cse01@telnet ~]$ ./[Link]


*** Parent is about to fork process ***
firstChild process starts (pid - 10213)
first child's Output,value - 1)
first child's Output,value - 2)
first child's Output,value - 3)
first child's Output,value - 4)
first child's Output,value - 5)
firstchild(pid - 10213)is about to exit

37
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

***Parent is about to fork process 2***


secondChild process starts (pid - 10214)
second child's Output,value - 1)
second child's Output,value - 2)
second child's Output,value - 3)
second child's Output,value - 4)
second child's Output,value - 5)
secondchild(pid - 10214)is about to exit
***Parent enters waiting status...
***Parent detects Process10213 was done***
***Parent detects process10214 is done***
***Parent exists***

Implementation of close system call


Program:
#include<unistd.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
int main()
{
int g;
g=creat("[Link]",S_IREAD/S_WRITE);
if(g==-1)
{
printf("error in opening [Link]");
}
else
{
printf("[Link] opened for read/write access");
printf("[Link] is currently empty");
}
close(g);
exit(0);
}

OUTPUT:
Thus [Link] opened for read or write access.
[Link] is currently empty.

Implementation of stat system call


Program:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

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

information for msg.c


.......
file size: 1066 bytes
no of links: 1file inode: 24384720

Implementation of opendir and readdir system calls


Program:

#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

VIVA VOCE QUESTIONS


1. Which of the following system calls does not return control to the calling point, on
termination?
a) fork
b) exec
c) ioctl
d) longjmp

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

[Link] of the following calls never returns an error ?


a) getpid
b) fork
c) ioctl
d) open
Answer: a

[Link] a thread invokes the exec system call,


a) only the exec executes as a separate process.
b) the program specified in the parameter to exec will replace the entire process
c) the exec is ignored as it is invoked by a thread.
d) none of the mentioned
Answer: b

[Link] exec is called immediately after forking,


a) the program specified in the parameter to exec will replace the entire process
b) all the threads will be duplicated
c) all the threads may be duplicated

40
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

d) none of the mentioned


Answer: a

[Link] a process does not call exec after forking,


a) the program specified in the parameter to exec will replace the entire process
b) all the threads should be duplicated
c) all the threads should not be duplicated
d) none of the mentioned
Answer: b
Explanation: The new process is purely based on fork, due to no exec command, duplication will
be done.

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

[Link]: 3 SIMULATE UNIX COMMANDS LIKE CP, LS, GREP


Objective:
To learn UNIX commands like cp, ls, grep
Aim:
To write C programs to simulate UNIX commands like cp, ls, grep, etc.

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:

The cp command is a command-line utility for copying files and directories. It


supports moving one or more files or folders with options for taking backups and
preserving attributes.

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

ls is a command to list computer files in Unix and Unix-like operating systems. ls is


specified by POSIX and the Single UNIX Specification. When invoked without any
arguments, ls lists the files in the current working directory.
ls is a utility for listing the files in a directory.

 grep, prints lines matching a certain pattern.


 grep <pattern> filename

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

Simulation of grep command


Program:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int calc_bufsize(char *filename)
{
struct stat st;
stat(filename, &st);
return ((int)st.st_size);
}
int main(int argc, char *argv[])
{
if(argc < 3)
{
printf("Usage:\n\t%s <word> <files> ...\n", argv[0]);
return -1;
}
FILE *fp;
char *filename;
int x = 2;
for(x; x != argc; x++)
{
filename = argv[x];
if( (fp = fopen(filename, "r")) == NULL)
{
printf("Failed to open file: %s\n", argv[2]);
return -2;
}
int BUFSIZE = calc_bufsize(filename);
char buf[BUFSIZE];
fread(&buf, sizeof(char), BUFSIZE, fp);
/* search buf for word (case sensitive) */

44
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

char *ans = strstr(buf, argv[1]);


/* word found, print filename */
if(ans != NULL)
{ printf("%s\n", filename);
printf("\n word is found");
/* word not found, do nothing */
fclose(fp);
}
else
printf("Word is not found\n");
}
return 0;
}

OUTPUT:
[cse01@telnet ~]$ cc ex3b1.c
[cse01@telnet ~]$ ./[Link] buf ex3b1.c
ex3b1.c

word is found

[IIcsea50@telnet ~]$ cc ex3b1.c


[IIcsea50@telnet ~]$ ./[Link] aaa ex3b1.c
Word is not found

VIVA VOCE QUESTIONS


This set of Unix Multiple Choice Questions & Answers (MCQs) focuses on “Copying a File: cp
Command”.

1. What is the function of cp command in UNIX?


a) list all the available files in the current directory
b) delete a given file
c) cp is a command used for copying files and directories
d) change the directory
Answer: c
$ cp file_01 file_02 // copies file_01 to file_02

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

c) destination file will be automatically created


d) none of the mentioned
View Answer

Answer: c

3. How can we copy a file into our current directory?


a) cp file1
b) cp file1
c) cp file*
d) none of the mentioned
Answer: b

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

[Link]: 4 SHELL PROGRAMMING


Objective:
 To learn Shell Program concept.
Aim:
To Write Shell Programming Using Vi Editor to Display Wishes Based on Time,
Biggest of Two Numbers, Biggest Among Three Numbers, String Comparison, Arithmetic
Operations, Sum of N Even Numbers, Sum of N Natural Numbers, Generation of Fibonacci
Series.
Introduction:
A text editor is a program that can be used to create and modify text files. One of
the most popular editors on Linux/Unix systems (it is also available on Windows and many
other platforms) is VI. There are many variations, with the most popular being vim.

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

Enter the text to search for.


Press <Return>.
The cursor moves to the first occurrence of that text.
To repeat the search in a forward direction, type
n
To repeat the search in a backward direction, type
N
Closing and Saving a File
With vi, you edit a copy of the file, rather than the original file. Changes are made to the
original only when you save your edits.
To save the file and quit vi, type
ZZ
The vi editor editor is built on an earler Unix text editor called ex. ex commands can be
used within vi. ex commands begin with a : (colon) and end with a <Return>. The command
is displayed on the status line as you type. Some ex commands are useful when saving and
closing files.
To save the edits you have made, but leave vi running and your file open:
Press <Esc>.
Type :w
Press <Return>.
To quit vi, and discard any changes your have made since last saving:
Press <Esc>.
Type :q!
Press <Return>.
Command Summary
STARTING vi
vi filename edit a file named "filename"
vi newfile create a new file named "newfile"
ENTERING TEXT
i insert text left of cursor
a append text right of cursor

53
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

MOVING THE CURSOR


h left one space
j down one line
k up one line
l right one space
BASIC EDITING
x delete character
nx delete n characters
X delete character before cursor
dw delete word
ndw delete n words
dd delete line
ndd delete n lines
D delete characters from cursor to end of line
r replace character under cursor
cw replace a word
ncw replace n words
C change text from cursor to end of line
o insert blank line below cursor
(ready for insertion)
O insert blank line above cursor
(ready for insertion)
J join succeeding line to current cursor line
nJ join n succeeding lines to current cursor line
u undo last change
U restore current line
MOVING AROUND IN A FILE
w forward word by word
b backward word by word
$ to end of line
0 (zero) to beginning of line

54
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

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
n repeat last search in same direction
N repeat last search in opposite direction
CLOSING AND SAVING A FILE
ZZ save file and then quit
:w save file
:q! discard changes and quit file
SYNTAX FOR LOOPING STATEMENTS
IF –THEN-ELSE CONSTRUCT
if [ condition]
then <action>
else
statements
fi (end of if)
WHILE
while <condition>
do
<statements>
Done
CASE
Case $<option> in
<statements>;;
<statements>;;

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

Display wishes based on time


~~~~~~~~~~~~~~~~~~~~~~
Time and Date at the moment is Fri 06 Mar 2009 [Link] PM IST
Good Afternoon
[Link] again.

Result:
Thus the time was found and a wish was displayed using the shell Program.

Ex no:4 b BIGGEST OF TWO NUMBERS

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

echo "Biggest Among Two numbers"


echo "~~~~~~~~~~~~~~~~~~~~~~ "
echo -n "Enter the first no:"
read a
echo -n "Enter the second no:"
read b
if [ $a -gt $b ]
then echo "The biggest no is:" $a
else echo "The biggest no is:" $b
fi

Output
[cse01@telnet ~]$ sh Biggest_Two

Biggest Among Two numbers


~~~~~~~~~~~~~~~~~~~~~~
Enter the first no:2
Enter the second no:3
The biggest no is: 3

57
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

[mtec11@telnet ~]$ sh Biggest_Two


Biggest Among Two numbers
~~~~~~~~~~~~~~~~~~~~~~~
Enter the first no:34
Enter the second no:7
The biggest no is: 34

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

echo "Biggest among three numbers"


echo "~~~~~~~~~~~~~~~~~~~~~~"
echo -n "Enter the first number:"
read a
echo -n "Enter the second number:"
read b
echo -n "Enter the third number:"
read c
if [ $a -gt $b -a $a -gt $c ]
then
echo "$a is greater."
elif [ $b -gt $c ]
then

58
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

echo " $b is greater. "


else
echo "$c is greater."
fi

Output

[cse01@telnet ~]$ sh Largest_Three


Largest among three numbers
~~~~~~~~~~~~~~~~~~~~~~
Enter the first number:45
Enter the second number:54
Enter the third number:55
55 is greater.

[mtec11@telnet ~]$ sh Largest_Three


Largest among three numbers
~~~~~~~~~~~~~~~~~~~~~~
Enter the first number:100
Enter the second number:12
Enter the third number:33
100 is greater.

[mtec11@telnet ~]$ sh Largest_Three


Largest among three numbers
~~~~~~~~~~~~~~~~~~~~~~
Enter the first number:12
Enter the second number:33
Enter the third number:21
33 is greater.

Result:
Thus the biggest of 3 numbers was found using the shell Program.

Ex No.4d String Comparison

Aim:

59
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

To write a shell Program for performing string comparison

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

echo "String Comparison"


echo "~~~~~~~~~~~~~~"
echo
echo -n "Enter The First String:"
read s1
echo
echo -n "Enter The Second String:"
read s2
echo
if [ $s1 == $s2 ]
then
echo The Given Strings $s1 and $s2 are equal
else
echo The Given Strings $s1 and $s2 are not equal
fi

Output

[cse01@telnet ~]$ sh String_Comparison


String Comparison
~~~~~~~~~~~~~~
Enter The First String:Shiva
Enter The Second String:Anandan
The Given Strings Shiva and Anandan are not equal

[cse01@telnet ~]$ sh String_Comparison


String Comparison
~~~~~~~~~~~~~~
Enter The First String:Sunil

60
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

Enter The Second String:sunil


The Given Strings Sunil and sunil are not equal
[cse01@telnet ~]$ sh String_Comparison

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.

Ex no: 4e Arithmetic Operations

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

Arithmetic Operation - Menu


[Link]
[Link]
[Link]
[Link]
[Link]
Enter your Choice:2
Option 2 Performs Subtraction
The difference of 12 and 12 is 0
[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:3
Option 3 Performs Multiplication
The product of 12 and 12 is 144
[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:4
Option 4 Performs Division
The Division of 12 by 12 is 1
[cse01@telnet ~]$ sh Arithmetic_Manipulation
Performing Arithmetic Manipulation
~~~~~~~~~~~~~~~~~~~~~~~~~~~

63
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

Enter the first no:12


Enter the second no:12
Arithmetic Operation - Menu
[Link]
[Link]
[Link]
[Link]
[Link]
Enter your Choice:0
You are exiting from the Arithmetic Manipulation
Thankyou. Visit again

Result:
Thus the arithmetic operations were performed using the shell Program.

Ex No: 4f Sum of n even numbers

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:

[cse01@telnet ~]$ sh even


-----------------------
Sum of n even numbers
-----------------------
enter the value of n
8
The sum of even numbers upto 8 is 20

Result:
Thus the sum of ‘ n ‘ even numbers was found using the shell Program.

Ex No:4g SUM OF ‘N’ NATURAL NUMBERS

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

[cse01@telnet ~]$ sh natural


-------------------------------
Sum of n natural numbers
-------------------------------
Enter the value of n
9
The sum of first 9 natural numbers is 45

Result:
Thus the sum of ‘ n ‘ natural numbers was found using the shell Program.

Ex no: 4h Generation of Fibonacci Series

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.

VIVA VOCE QUESTIONS

67
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

1. What is a text editor?


A text editor is a program that can be used to create and modify text files. One of
the most popular editors on Linux/Unix systems (it is also available on Windows and
many other platforms) is VI. There are many variations, with the most popular being
vim.
2. Define 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
3. Explain the steps to close and saving a file.
 ZZ save file and then quit
 :w save file
 :q! discard changes and quit file
4. Define the Syntax for WHILE statement.
while <condition>
do
<statements>
Done
5. Define the Syntax for CASE statement.
Case $<option> in
<statements>;;
<statements>;;
.. .
.
*) <error statement>;;
esac

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.

EX: NO:5 CPU SCHEDULING ALGORITHMS

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

 Shortest Remaining Time

 Round Robin(RR) Scheduling

 Multiple-Level Queues 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

The round-robin (RR) scheduling algorithm is designed especially for timesharing


systems. It is similar to FCFS scheduling, but preemption is added to enable the system to
switch between processes. A small unit of time, called a time quantum or time slice, is
defined. A time quantum is generally from 10 to 100 milliseconds in length. The ready
queue is treated as a circular queue. The CPU scheduler goes around the ready queue,
allocating the CPU to each process for a time interval of up to 1 time quantum.
To implement RR scheduling, we again treat the ready queue as a FIFO queue of
processes. New processes are added to the tail of the ready queue. The CPU scheduler picks
the first process from the ready queue, sets a timer to interrupt after 1 time quantum, and
dispatches the process.
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]

5A).Implementation of FCFS algorithm


Aim:-
To write a c program to implement the FCFS scheduling algorithm.
Algorithm:-
1. Start the program
2. Initialize the float variable float wt,tot tn.
[Link] the no. of process to be executed.
[Link] the burst time and turnaround time.
[Link] the avg waiting time.
6. Stop the program.
Program:
#include<stdio.h>
int main()
{
int i,j,n,ch,ts,count,ptm,flag;
float tot_wt,tot_tn;

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.

5B).Implementation of SJF algorithm


Aim:-
To write a c program to implement the SJF scheduling algorithm.
Algorithm:-
1. Start the program
2. Initialize the float variable tot wt, tot tn=0.
[Link] the no. of process to be executed.
[Link] the burst time.
[Link] the avg waiting time.
6. Stop the program.
Program:
#include<stdio.h>
int main()
{
int i,j,n,ch,ts,count,ptm,flag;

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);
}

"exp4b.c" 53L, 925C written


Output :
[cse01@telnet ~]$ cc exp4b.c
[cse01@telnet ~]$ ./[Link]
SJF scheduling
Enter the no of process
4
Enter the burst time of process 1
1
Enter the burst time of process 2
2
Enter the burst time of process 3
3
Enter the burst time of process 4
4
Process no Burst time Waiting time Turnaroundtime
1 1 0 1
2 2 1 3
3 3 3 6
4 4 6 10
Avg waiting time 2.500000
Avg turnaround time 5.000000

Result:-
Thus the c program for implementation of SJF scheduling algorithm was executed
and the output was verified successfully.

5C).Implementation of priority scheduling algorithm


Aim:-
To write a c program to implement the Priority scheduling algorithm.
Algorithm:-

75
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

1. Start the program


2. Initialize the float variable tot wt, tot tn=0.
[Link] the no. of process to be executed.
[Link] the burst time and turnaround time.
[Link] the avg waiting time.
6. Stop the program.
Program:
#include<stdio.h>
void main()
{
int i,j,n,ch,ts,count,ptm,flag;
float tot_wt,tot_tn;
struct process
{
int pno;
int btime;
int wtime;
int ttime;
int rrtime;
int pri;
}p[10],temp;
printf("Priority Scheduling\n");
tot_wt=tot_tn=0;
printf("Enter the no of processes\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);
printf("Enter the Priority of process %d\n",i+1);
scanf("%d",&p[i].pri);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(p[i].pri>p[j].pri)
{
temp=p[i];

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.

5D).Implementation of Round Robin algorithm


Aim:-
To write a c program to implement the Round Robin scheduling algorithm.
Algorithm:-
1. Start the program
2. Initialize the float variable tot_wt, tot_tn.
[Link] the no. of process to be executed.
[Link] the burst time and turnaround time.
[Link] the avg waiting time.
6. Stop the program.
Program:
#include<stdio.h>
void main()
{
int i,j,n,ch,ts,count,ptm,flag;
float tot_wt,tot_tn;
struct process
{
int pno;
int btime;

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

VIVA VOCE QUESTIONS


1. Explain First-Come, First-Served Scheduling.
With this scheme, the process that requests the CPU first is allocated the CPU first.
2. Define Shortest-Job-First Scheduling.

80
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

A different approach to CPU scheduling is the shortest-job-first (SJF) scheduling


algorithm. 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.
3. What is Priority Scheduling?
The SJF algorithm is a special case of the general priority-scheduling algorithm. Apriority
is associated with each process, and the CPU is allocated to the process with the highest
priority. Equal-priority processes are scheduled in FCFS order.
4. Explain Round-Robin Scheduling.
The round-robin (RR) scheduling algorithm is designed especially for timesharing
systems. It is similar to FCFS scheduling, but preemption is added to enable the system to
switch between processes. A small unit of time, called a time quantum or time slice, is
defined. A time quantum is generally from 10 to 100 milliseconds in length. The ready
queue is treated as a circular queue. The CPU scheduler goes around the ready queue,
allocating the CPU to each process for a time interval of up to 1 time quantum.
5. Define preemption and non preemption.
Under non preemptive scheduling, once the CPU has been allocated to a process, the
process keeps the CPU until it releases the CPU either by terminating or by switching to the
waiting state.
Under preemptive scheduling, once the CPU has been allocated to a process, the
process keeps the CPU until another process of higher priority requests for the CPU waiting
in the ready queue. The highest priority process should always be the process that is
currently utilized.
6. What are the criteria used for CPU Scheduling?
 CPU utilization:
CPU utilization can range from 0 to 100 percent
 Throughput:
One measure of work is the number of processes that are completed per time
unit.
 Turnaround time:
The interval from the time of submission of a process to the time of completion
 Waiting time:
Waiting time is the sum of the periods spent waiting in the ready queue.
 Response time:
Time from the submission of a request until the first response is produced

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

printf("\n\n\t Producer Consumer Relationship \n\n");


printf("Enter the Buffer Size:");
scanf("%d",&n);
empty = n;
do
{
printf("\n\n [Link] \t [Link] \t [Link]\n");
printf("\nEnter ur choice:");
scanf("%d",&option);
switch(option)
{
case 1:
if(full == n)
printf("Producer cannot produce, Buffer is full");
else
{
printf("\n Item to be Produced:");
scanf("%s",buf[full]);
empty--;
mutex--;
printf("\nProduced item is %s",buf[full]);
mutex++;
full++;
}
break;
case 2:
if(empty == n)
printf("\n Consumer cannot consume, Buffer is empty");
else
{
full--;
mutex--;
printf("\n\n Consumer wants to be consumer %s",buf[full]);
mutex++;
empty++;
printf("\n\n Consumer consumed %s",buf[full]);
}
break;
case 3:
exit(0);

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

Produced item is doss


[Link] [Link] [Link]

Enter ur choice:1
Item to be Produced:maran

Produced item is maran

[Link] [Link] [Link]

Enter ur choice:1
Producer cannot produce, Buffer is full

[Link] [Link] [Link]

Enter ur choice:2
Consumer wants to be consumer maran

Consumer consumed maran

[Link] [Link] [Link]

Enter ur choice:2

Consumer wants to be consumer doss

Consumer consumed doss

[Link] [Link] [Link]


Enter ur choice:2

86
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

Consumer cannot consume, Buffer is empty

[Link] [Link] [Link]

Enter ur choice:3

VIVA VOCE QUESTIONS


1. What is Semaphore? State the two parameters.
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 S++;
wait }
S--;
}

2. Define Mutual Exclusion.


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 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. If process Pi is executing in its
critical section, then no other processes can be executing in their critical sections which
property is called mutual exclusion.
3. Define 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.
4. Explain the Semaphore Usage and 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.
5. List the requirements of critical-section problem.
 Mutual exclusion.
 Progress.
 Bounded waiting.

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.

Ex. No: 7 Implementation of shared memory and Inter Process Communication


Objective:
 To know how to implement Shared memory and IPC Concept.
Aim:-
To write a c program to implement the shared memory.
Introduction:
In computer science, shared memory is memory that may be simultaneously
accessed by multiple programs with intent to provide communication among them or avoid
redundant copies. Shared memory is an efficient means of passing data between
programs.
Interprocess communication (IPC) is a set of programming interfaces that allow a
programmer to coordinate activities among different program processes that can run
concurrently in an operating system. This allows a program to handle many user requests
at the same time.
Definition:
Inter-process communication or interprocess communication (IPC) refers
specifically to the mechanisms an operating system provides to allow processes it manages
to share data. Typically, applications can use IPC, categorized as clients and servers, where
the client requests data and the server responds to client requests.
Shared memory is the fastest interprocess communication mechanism. The
operating system maps a memory segment in the address space of several processes, so
that several processes can read and write in that memory segment without calling
operating system functions. However, we need some kind of synchronization between
processes that read and write shared memory.
Theory:
Processes executing concurrently in the operating system may be either
independent processes or cooperating processes. A process is independent if it cannot
affect or be affected by the other processes executing in the system. Any process that
does not share data with any other process is independent.
A process is cooperating if it can affect or be affected by the other processes
executing in the system. Cooperating processes require an interprocess communication
(IPC) mechanism that will allow them to exchange data and information. There are two

88
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

fundamental models of interprocess communication: shared memory and message


passing.
Shared Memory Model:
A region of memory that is shared by cooperating processes is established.
Processes can then exchange information by reading and writing data to the shared
region.
Message passing model:
In the message-passing model, communication takes place by means of messages
exchanged between the cooperating processes.
Two communications models are contrasted in Figure below.

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

Implementation of Inter process communication using pipes

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

Implementation of Inter process communication using signals


Aim:-
To write a c program to implement the Inter process communication using signals.
Algorithm:-

92
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

1. Start the program


[Link] a parent process pid using fork() and send signals to child process if
pid=0,signals such as SIGHUP,SIGINT,SIGQUIT to terminate the child process and if
pid not equal to zero then it equals born the parent and child process.
3. Stop the program.
Program:
include<stdio.h>
#include<signal.h>
void sighup();
void sigint();
void sigquit();
main()
{
int pid;
if((pid=fork())<0){
perror("fork");
exit(1);
}
if(pid==0)
{
signal(SIGHUP,sighup);
signal(SIGINT,sigint);
signal(SIGQUIT,sigquit);
for(;;);
}
else
{
printf("\n PARENT:sending SIGHUP\n\n");
kill(pid,SIGHUP);
sleep(3);
printf("\n PARENT:sending SIGINT\n\n");
kill(pid,SIGINT);
sleep(3);
printf("\nPARENT:sending SIGQUIT\n\n");
kill(pid,SIGQUIT);
sleep(3);
}
void sighup()
{
signal(SIGHUP,sighup);

93
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

printf("CHILD:i have received a SIGHUP\n");


}
void sigint()
{
signal(SIGINT,sigint);
printf("CHILD:i have received a SIGINT\n");
}
void sigquit()
{
printf("MY daddy has killed me....");
exit(0);
}
Output:
[cse01@telnet ~]$ cc ex6b.c
[cse01@telnet ~]$ ./[Link]

PARENT: sending SIGHUP


CHILD: i have received a SIGHUP
PARENT: sending SIGINT
CHILD: i have received a SIGINT
PARENT: sending SIGQUIT
MY daddy has killed me...

Implementation of Inter process communication using message queue


Aim:-
To write a c program to implement the Inter process communication using message
queue.
Algorithm:-
1. Start the program.
[Link] a message queue unique message() system call and getpid id.
3. Send a msg to the queue by using message system call.
[Link] a new process using fork() and store it in pid.
[Link] it is a child process do the following.
a)receive one message from the queue using msgrcv().
b)send another message to the queue send().
c)receive that msg from queue using msgrcv() system call and display.
[Link] the program.
Program:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>

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

VIVA VOCE QUESTIONS


1. What is Inter Process Communication?
Processes executing concurrently in the operating system may be either
independent processes or cooperating processes. A process is independent if it cannot
affect or be affected by the other processes executing in the system. Any process that
does not share data with any other process is independent.
A process is cooperating if it can affect or be affected by the other processes
executing in the system. Cooperating processes require an interprocess communication
(IPC) mechanism that will allow them to exchange data and information. There are two
fundamental models of interprocess communication: shared memory and message
passing.
2. Explain Shared Memory Model.
A region of memory that is shared by cooperating processes is established.
Processes can then exchange information by reading and writing data to the shared
region.

96
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

3. What is Message passing model?


In the message-passing model, communication takes place by means of messages
exchanged between the cooperating processes.
4. List the types of Buffers.
The unbounded buffer places no practical limit on the size of the buffer. The
consumer may have to wait for new items, but the producer can always produce new
items.
The bounded buffer assumes a fixed buffer size. In this case, the consumer must
wait if the buffer is empty, and the producer must wait if the buffer is full.
5. Explain Message-Passing Systems.
Message passing provides a mechanism to allow processes to communicate and
to synchronize their actions without sharing the same address space. It is particularly
useful in a distributed environment, where the communicating processes may reside on
different computers connected by a network. Forexample, an Internet chat program
could be designed so that chat participants communicate with one another by
exchanging messages.
A message-passing facility provides at least two operations:
o send(message)
o receive(message)
Messages sent by a process can be either fixed or variable in size. If only fixed-
sized messages can be sent, the system-level implementation is straightforward. If
processes P and Q want to communicate, they must send messages to and receive
messages from each other: a communication link must exist between them. This link
can be implemented in a variety of ways.
 Direct or indirect communication
 Synchronous or asynchronous communication
 Automatic or explicit buffering
6. What is Synchronization?
Message passing may be either blocking or nonblocking also known as
synchronous and asynchronous.
• Blocking send: The sending process is blocked until the message is received by the
receiving process or by the mailbox.
• Nonblocking send. The sending process sends the message and resumes operation.
• Blocking receive. The receiver blocks until a message is available.
• Nonblocking receive. The receiver retrieves either a valid message or a null.

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.

[Link] Implementation of Banker’s Algorithm for Deadlock Avoidance


Objective:
 To learn about deadlock avoidance
 To know about the bankers algorithm
 To implement the bankers algorithm in deadlock avoidance.
Aim:
To avoid deadlock situation using Banker’s algorithm.
Introduction:
Claim edge converts to request edge when a process requests a resource. When a
resource is released by a process, assignment edge reconverts to a claim edge. Resources
must be claimed a priori in the system. Resource-Allocation Graph for Deadlock
Avoidance.
Definition:
Both processes need resources to continue execution. In an operating system, a
deadlock occurs when a process or thread enters a waiting state because a requested
system resource is held by another waiting process, which in turn is waiting for another
resource held by another waiting process.
Theory:
The resource-allocation-graph algorithm is not applicable to a resource allocation
system with multiple instances of each resource type. The deadlock avoidance algorithm
that we describe next is applicable to such a system but is less efficient than the resource-
allocation graph scheme. This algorithm is commonly known as the banker’s algorithm.
Data Structures:
Several data structures must be maintained to implement the banker’s
[Link] are:
Available:
A vector of length m indicates the number of available resources of each type. If
Available[j] equals k, then k instances of resource type Rjare available.
Max:
An n × m matrix defines the maximum demand of each process. If Max[i][j] equals k,
then process Pi may request at most k instances of resource type Rj.
Allocation:

98
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

An n × m matrix defines the number of resources of each type currently allocated to


each process. If Allocation[i][j] equals k, then process Pi is currently allocated k instances
of resource type Rj.
Need:
An n × m matrix indicates the remaining resource need of each process. If Need[i][j]
equals k, then process Pi may need k more instances of resource type Rjto complete its
task. Note that Need[i][j] equals Max[i][j] − Allocation[i][j].
Safety Algorithm:
We can now present the algorithm for finding out whether or not a system is in a
safe state. This algorithm can be described as follows:
1. LetWorkand Finish be vectors of length m and n, respectively. Initialize Work =
Available and Finish[i] = false for i = 0, 1, ...,n− 1.
2. Find an index i such that both
a. Finish[i] == false
b. Needi≤Work
If no such i exists, go to step 4.
3. Work =Work + Allocation
Finish[i] = true
Go to step 2.
4. If Finish[i] == true for all i, then the system is in a safe state.
Resource-Request Algorithm:
We describe the algorithm for determining whether requests can be safely granted.
Let Requestibe the request vector for process Pi . If Requesti[ j] == k, then process
Pi wants k instances of resource type Rj. When a request for resources is made by process
Pi , the following actions are taken:
1. If Requesti≤Needi, go to step 2. Otherwise, raise an error condition, since the process
has exceeded its maximum claim.
2. If Requesti≤ Available, go to step 3. Otherwise, Pi must wait, since the resources are not
available.
3. Have the system pretend to have allocated the requested resources to process Pi by
modifying the state as follows:
Available = Available–Requesti;
Allocationi= Allocationi+ Requesti;
Needi= Needi–Requesti;
Software Required:
 Turbo C or telnet.
Procedure:
 Goto turbo C
 Compile the C program by compile.
 Run the C program by run.
99
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.

Resource – request algorithm


1. If Request i < = Needi , go to step 2. Otherwise, error
2. If Request i < = Available, go to step 3. Otherwise, Pi must wait, since resources are not
available
3. Modify the state ( the system pretend to have allocated the requested resources to
process Pi )
Available = Available - Requesti
Allocationi = Allocationi + Requesti
Needi = Needi - Requesti
4. If the resulting state is safe, the transaction is completed and process Pi is allocated its
resources. If
new state is unsafe, then Pi must wait for Requesti and the old state is restored.
5. Stop.

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

VIVA VOCE QUESTIONS


1. What is a deadlock? Give the necessary conditions for deadlock.
A process requests resources; if the resources are not available at that time, the
process enters a waiting state. Sometimes, a waiting process is never again able to change
state. This situation is called a deadlock.
2. Explain the Conditions of deadlock.
1. Mutual Exclusion
2. Hold and wait
3. No preemption

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.

Ex. No: 9 Implementation of Deadlock Detection


Objective:
 To learn about deadlock.
 To detect deadlock by using algorithm.
Aim
To write a C program to implement the deadlock detection.
Introduction:
Deadlock detection is the process of actually determining that a deadlock exists
and identifying the processes and resources involved in the deadlock. The basic idea is to
check allocation against resource availability for all possible allocation sequences to
determine if the system is in deadlocked state.
Definition:
A deadlock is a situation in which two computer programs sharing the same
resource are effectively preventing each other from accessing the resource, resulting in
both programs ceasing to function. The earliest computer operating systems ran only one
program at a time.
Theory:
Deadlock Detection:
System should provide the following when deadlock occurs:
 An algorithm that examines the state of the system to determine whether a deadlock
has occurred
 An algorithm to recover from the deadlock
Single Instance of Each Resource Type:
If all resources have only a single instance, then we can define a deadlock detection
algorithm that uses a variant of the resource-allocation graph, called a wait-for graph.
More precisely, an edge from Pi to Pjin a wait-for graph implies that process Pi is
waiting for process Pjto release a resource that Pi needs. An edge Pi → Pjexists in a wait-for
graph if and only if the corresponding resource allocation graph contains two edges Pi →
Rqand Rq→ Pjfor some resource Rq. In Figure below, we present a resource-allocation
graph and the corresponding wait-for graph.
As before, a deadlock exists in the system if and only if the wait-for graph contains a
cycle. To detect deadlocks, the system needs to maintain the wait for graph and
periodically invoke an algorithm that searches for a cycle in the graph.
Several Instances of a Resource Type:
105
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

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.

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]

Alg I: Simply detects the existence of a Cycle:


1. Start at any vertex finds all its immediate neighbors.
2. From each of these find all immediate neighbors, etc.
3. Until a vertex repeats (there is a cycle) or one cannot continue (there is no cycle).
4. Stop.

Alg 2: On a copy of the graph:


1. See if any Processes NEEDs can all be satisfied.
2. If so satisfy the needs with holds and remove that Process and all the Resources it holds
from the graph.
3. If any Process are left Repeat step 1
4. If all Processes are finally removed by this procedure there is no Deadlock in the original
graph, if not there is.
5. Stop.

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

enter resource vector :


21121
enter the availability vector :
00001

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]

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

VIVA VOCE QUESTIONS


1. Define Deadlock Detection.
System should provide the following when deadlock occurs:
 An algorithm that examines the state of the system to determine whether a deadlock
has occurred
 An algorithm to recover from the deadlock
2. What is Single Instance of Each Resource Type?
If all resources have only a single instance, then we can define a deadlock detection
algorithm that uses a variant of the resource-allocation graph, called a wait-for graph
An edge Pi → Pjexists in a wait-for graph if and only if the corresponding resource
allocation graph contains two edges Pi → Rqand Rq→ Pjfor some resource Rq. In Figure
below, we present a resource-allocation graph and the corresponding wait-for graph. As
before, a deadlock exists in the system if and only if the wait-for graph contains a cycle.

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

Ex. No: 10 Implementation of Threading and Synchronization Applications


Objective:
 To know about Threading and synchronization concept.
 To implement threading and synchronization.
Aim:
To implement Threading and synchronization applications.
Introduction:
A thread is a basic unit of CPU utilization, consisting of a program counter, a stack,
and a set of registers, ( and a thread ID. ) Traditional ( heavyweight ) processes have a
single thread of control - There is one program counter, and one sequence of instructions
that can be carried out at any given time.
Process Synchronization means sharing system resources by processes in such a
way that, Concurrent access to shared data is handled thereby minimizing the chance of
inconsistent data. Process Synchronization was introduced to handle problems that arose
while multiple process executions
Definition:
A thread is the smallest unit of processing that can be performed in an OS. In most
modern operating systems, a thread exists within a process - that is, a single process may
contain multiple threads.
Process Synchronization: The simultaneous execution of multiple threads or
processes to reach a handshake such that they commit a certain sequence of actions. Lock,
mutex, and semaphores are examples of process synchronization
Theory:
Multi Threading models available in OS:
A relationship must exist between user threads and kernel threads. There are three
common ways of establishing such a relationship: the many-to-one model, the one-to-one
model, and the many-to many models.
Many-to-One Model:
This model maps many user-level threads to one kernel thread. Thread
management is done by the thread library in user space, so it is efficient.
One-to-One Model:
The one-to-one model maps each user thread to a kernel thread. It provides more
concurrency than the many-to-one model by allowing another thread to run when a thread
makes a blocking system call. It also allows multiple threads to run in parallel on
multiprocessors. The only drawback to this model is that creating a user thread requires
creating the corresponding kernel thread.
Many-to-Many Model: The many-to-many model multiplexes many user-level threads to a
smaller or equal number of kernel threads. The number of kernel threads may be specific
to either a particular application or a particular machine.

114
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

Many-to-one model One-to-one model Many-to-Many model

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];

void* doSomeThing(void *arg)


{
unsigned long i = 0;
pthread_t id = pthread_self();

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

printf("\ncan't create thread :[%s]", strerror(err));


else
printf("\n Thread created successfully\n");

i++;
}

sleep(5);
return 0;
}

OUTPUT:
$ ./threads
Thread created successfully
First thread processing
Thread created successfully

But if I run it with sleep() enabled then I see the output as :


$ ./threads
Thread created successfully
First thread processing
Thread created successfully
Second thread processing

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

pthread_t tid[2];
int counter;

void* doSomeThing(void *arg)


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

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

117
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

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

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

Pthread Creation and Termination


#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5

void *PrintHello(void *threadid)


{

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);
}

int main (int argc, char *argv[])


{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}

/* Last thing that main() should do */


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

Thread 7: Latin: Orbis, te saluto! Sum=28

VIVA VOCE QUESTIONS


1. Explain the Multi Threading models available in OS.
 Many-to-One Model:
This model maps many user-level threads to one kernel thread. Thread
management is done by the thread library in user space, so it is efficient.
 One-to-One Model:
The one-to-one model maps each user thread to a kernel thread. It provides more
concurrency than the many-to-one model by allowing another thread to run when a thread
makes a blocking system call. It also allows multiple threads to run in parallel on
multiprocessors. The only drawback to this model is that creating a user thread requires
creating the corresponding kernel thread.
 Many-to-Many Model:
The many-to-many model multiplexes many user-level threads to a smaller or equal
number of kernel threads. The number of kernel threads may be specific to either a
particular application or a particular machine.
2. What is 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.
3. What are differences between user level threads and kernel level threads? Under
what circumstances is one type better than the other?
(1) User-level threads are unknown by the kernel, whereas the kernel is aware of
kernel threads.(2) On systems using eitherM:1 or M:N mapping, userthreads are scheduled
by the thread library and the kernel schedules kernel threads. (3) Kernel threads need not
be associated with a process whereas every user thread belongs to a process. Kernel
threads are generally more expensive to maintain than user threads as they must be
represented with a kernel data structure

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

Thus the c program for implementation of threading and synchronization


application was executed and the output was verified successfully.

Ex. No: 11 Implementation of Memory Allocation Methods

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();

printf("\n\tMemory Management Scheme - First 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);

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

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
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();

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)
{
temp=b[j]-f[i];
if(temp>=0)
if(lowest>temp)
{
ff[i]=j;
lowest=temp;
}
}
}
frag[i]=lowest;
bf[ff[i]]=1;

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

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
Fragme
File No File Size Block No Block Size nt
1 1 2 2 1
2 4 1 5 1

VIVA VOCE QUESTIONS


Given six memory partitions of 300 KB, 600 KB, 350 KB, 200 KB, 750 KB,and 125 KB (in
order),How would the first-fit, best-fit, and worst-fit algorithms place processes of size 115 KB,
500 KB, 358 KB, 200 KB, and 375 KB (in order)? Rank the algorithms in terms of how
efficiently they use memory. Nov/Dec 2010

Best Fit: 300

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

Ex. No: 12 Implementation of Paging Technique of Memory Management

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.

Hashed Page Tables:


A common approach for handling address spaces larger than 32 bits is to use a hashed
page table, with the hash value being the virtual page number. Each entry in the hash table
contains a linked list of elements that hash to the same location (to handle collisions). Each
element consists of three fields: (1) the virtual page number, (2) the value of the mapped
page frame, and (3) a pointer to the next element in the linked list.
Inverted Page Tables:

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

enter the size of each page:3


logical address content
---------------------------------
0 A
B
C
----------------------------------
1 D
E
F
---------------------------------
2 G
H
I
-----------------------------------

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

logical address physical address


0 6
1 9
2 3
3 0
enter the logical address:
2
enter the displacement 0-2:1
data is :H
physical address is 4

VIVA VOCE QUESTIONS


1. How to implement Paging Paging?
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. When a process is to be executed, its pages are loaded into any available
memory frames from their source (a file system or the backing store). The backing store is
divided into fixed-sized blocks that are the same size as the memory frames or clusters of
multiple frames

133
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

2. Define 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.
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

Ex. No: 13 Page Replacement Algorithms


Objective:
 To learn about paging concept.
 To know about various page replacement techniques.
Introduction:
In a computer operating system that uses paging for virtual memory management,
page replacement algorithms decide which memory pages to page out (swap out, write
to disk) when a page of memory needs to be allocated.
Definition:
 When there is a page fault, the referenced page must be loaded.
 If there is no available frame in memory, then one page is selected for replacement

 If the selected page has been modified, it must be copied back to disk (swapped out)

 A page replacement algorithm is said to satisfy the inclusion property or is called a


stack algorithm if the set of pages in a k-frame memory is always a subset of the
pages in a (k + 1) frame memory.

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.

Optimal Page Replacement

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.

Unfortunately, the optimal page-replacement algorithm is difficult to implement,


because it requires future knowledge of the reference string. As a result, the optimal
algorithm is used mainly for comparison studies.

LRU Page Replacement (least recently used (LRU))

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]

13.a. FIFO page replacement algorithm

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

10. Stop the process

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.

13.b. LRU page replacement algorithm

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.

13.c. LFU page replacement algorithm

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;

printf("Enter no of frames : ");


scanf("%d",&f);
printf("Enter no of pages : ");
scanf("%d",&p);

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 ::

VIVA VOCE QUESTIONS

1. What is Page fault?


While the process executes and accesses pages that are memory resident, execution
proceeds normally. But if the process tries to access a page that was not brought into
memory then it causes a page fault. The paging hardware, in translating the address
through the page table, will notice that the invalid bit is set, causing a trap to the operating
[Link] procedure for handling this page fault is straight forward and it is as follows:
 If the reference was invalid, we terminate the process. If it was valid but we have not
yet brought in that page, we now page it in.
 We find a free frame (by taking one from the free-frame list, for example).
 We schedule a disk operation to read the desired page into the newly allocated
frame.

2. Explain Page frame.


Paging is another memory-management scheme that offers the advantage of permitting
the physical address space of a process to be non-contiguous. 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. When a
process is to be executed, itspages are loaded into any available memory frames from their
source.

145
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

3. What is 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. When a page must be replaced, the oldest page is chosen. It is not
strictly necessary to record the time when a page is brought in. We can create a FIFO queue
to hold all pages in memory. We replace the page at the head of the queue. When a page is
brought into memory, we insert it at the tail of the queue.

4. What is LRU Page Replacement? (least recently used (LRU))


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.

5. What is Least frequently used (LFU)?


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.

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

[Link].14 Implementation of File Organization Techniques


Objective:
 To learn the various techniques of file organization.
Introduction:
Given that a file consists, generally speaking, of a collection of records, a key element
in file management is the way in which the records themselves are organized inside the file,
since this heavily affects system performances ad far as record finding and access.
Definition:
The term "file organization" refers to the way in which data is stored in a file and,
consequently, the method(s) by which it can be accessed. This COBOL system supports
three file organizations: sequential, relative and indexed.
Theory:
Directory Structure
There are five directory structures. They are
1. Single-level directory
2. Two-level directory
3. Tree-Structured directory
4. Acyclic Graph directory
5. General Graph directory
1. Single – Level Directory
The simplest directory structure is the single- level directory. All files are contained in
the same directory.
2. Two – Level Directory
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.
When a user refers to a particular file, only his own UFD is searched. Thus, different
users may have files with the same name, as long as all the file names within each UFD
are unique. To create a file for a user, the operating system searches only that user’s
UFD to ascertain whether another file of that name exists. To delete a file, the operating
system confines its search to the local UFD; thus, it cannot accidentally delete another
user’s file that has the same name. The user directories themselves must be created and
deleted as necessary.A special system program is run with the appropriate user name
and account information. The program creates a new UFD and adds an entry for it to
theMFD.
3. 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,

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]

14.a Single level directory

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:

Enter name of dir/file(under root):ROOT


Enter 1 for Dir/2 for file:1
No of sub directories/files(for ROOT):3
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):0
Enter name of dir/file(under ROOT):USER2
Enter 1 for Dir/2 for file:1
No of sub directories/files(for USER2):0
Enter name of dir/file(under ROOT):USER3
Enter 1 for Dir/2 for file:1
No of sub directories/files(for USER3):0

Result:-
Thus the c program to implement the Single level directory file organization
techniques was executed and the output was verified successfully.

14.b. Two-level directory Structure

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.

14.c. Hierarchical directory Structure

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

Enter 1 for Dir/2 for file:1


No of sub directories/files(for VB):2
Enter name of dir/file(under VB):A
Enter 1 for Dir/2 for file:2
No of sub directories/files(for VB):B
Enter 1 for Dir/2 for file:2
Enter name of dir/file(under USER1):C
Enter 1 for Dir/2 for file:2
Enter name of dir/file(under ROOT): USER2
Enter 1 for Dir/2 for file:1
No of sub directories/files(for USER2):1
Enter name of dir/file(under USER2):JAVA
Enter 1 for Dir/2 for file:1
No of sub directories/files(for JAVA):2
Enter name of dir/file(under JAVA):D
Enter 1 for Dir/2 for file:2
Enter name of dir/file(under JAVA):HTML
Enter 1 for Dir/2 for file:1
No of sub directories/files(for HTML):0
How many links:2
File/Dir:B
User name:USER2
File/Dir:HTML
User name:USER1

VIVA VOCE QUESTIONS


1. Define Mounting.
A file system must be mounted before it can be available to processes on the system.
The mount procedure is straightforward. The operating system is given the name of the
device and the mount point—the location within the file structure where the file system
is to be attached.
2. Explain Single – Level Directory.
The simplest directory structure is the single- level directory. All files are contained
in the same directory.
Disadvantage: When the number of files increases or when the system has more
than one user, since all files are in the same directory, they must have unique names.
Even a single user on a single-level directory may find it difficult to remember the
names of all the files as the number of files increases.
3. Explain Two – Level Directory.

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

[Link] :15 Implementation of File Allocation Strategies


Objective:
 To learn the various file allocation strategies.
Introduction:
The direct-access nature of disks gives us flexibility in the implementation of files. In
almost every case, many files are stored on the same disk. The main problem is how to
allocate space to these files so that disk space is utilized effectively and files can be
accessed quickly. Three major methods of allocating disk space are in wide use: contiguous,
linked, and indexed. Each method has advantages and disadvantages. Although some
systems support all three, it is more common for a system to use one method for all files
within a file-system type.
Definition:
The direct-access nature of disks gives us flexibility in the implementation of files. In
almost every case, many files are stored on the same disk. The main problem is how to
allocate space to these files so that disk space is utilized effectively and files can be
accessed quickly.
Theory:
Contiguous allocation requires that each file occupy a set of contiguous blocks on the disk.
Disk addresses define a linear ordering on the disk. With this ordering, assuming that only
one job is accessing the disk, accessing block b +1 after block b normally requires no head
movement. When head movement is needed (from the last sector of one cylinder to the
first sector of the next cylinder), the head need only move from one track to the next. Thus,
the number of disk seeks required for accessing contiguously allocated files is minimal, as
is seek time when a seek is finally needed.
If the file is n blocks long and starts at locationb, then it occupies blocks b, b + 1, b + 2, ...,b +
n − 1. The directory entry for each file indicates the address of the starting block and the
length of the area allocated for this file

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]

4.a. Sequential File Allocation

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

4.b. Indexed File Allocation:


Aim:
To implement Indexed file allocation technique in C.
Algorithm:
1. Start
2. Declare the index block no. and total [Link] files in a block
3. Get the index block no. and total [Link] files in a block from the user.
4. Allocate files based on the index block no.
5. Arrange the files based on indexes which are created for each fragment of the file such
that each and every similar indexed file is maintained by the primary index to provide the
flow to file
fragments.
6. stop

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:

VIVA VOCE QUESTIONS

172
FXEC, IT, IT6412 – OPERATING SYSTEMS LAB

1. Differentiate the various file access methods.


The different types of accessing a file are:
 Sequential access: Information in the file is accessed sequentially .Direct
access: Information in the file can be accessed without any particular order.
 Other access methods: Creating index for the file, indexed sequential access
method (ISAM) etc.
2. What is meant by free space management?
Since disk space is limited, we need to reuse the space from deleted files for new
files, if possible. (Write-once optical disks allow only one write to any given sector,
and thus reuse is not physically possible.) To keep track of free disk space, the
system maintains a free-space list. The free-space list records all free disk blocks —
those not allocated to some file or directory. To create a file, we search the free-
space list for the required amount of space and allocate that space to the new file.
This space is then removed from the free-space list. When file is deleted, its disk
space is added to the free-space list.
3. What is Contiguous Allocation?
Contiguous allocation requires that each file occupy a set of contiguous blocks
on the disk. Disk addresses define a linear ordering on the disk. With this ordering,
assuming that only one job is accessing the disk, accessing block b +1 after block b
normally requires no head movement. When head movement is needed (from the last
sector of one cylinder to the first sector of the next cylinder), the head need only move
from one track to the next.
4. Explain Linked Allocation.
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.
5. Define Indexed allocation.
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 addresses. The entry in the index block points to the

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

You might also like