Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
34 views153 pages

OS Lab Manual-R2021 New

The document is an Operating Systems Lab Manual from the Department of Information Technology, detailing a list of experiments related to operating systems, including installations of Linux and Windows, process management, CPU scheduling algorithms, inter-process communication, and memory allocation methods. It provides step-by-step instructions for installing Ubuntu and Windows 10, as well as basic UNIX commands and shell programming. The manual serves as a comprehensive guide for students to explore and implement various operating system concepts and techniques.

Uploaded by

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

OS Lab Manual-R2021 New

The document is an Operating Systems Lab Manual from the Department of Information Technology, detailing a list of experiments related to operating systems, including installations of Linux and Windows, process management, CPU scheduling algorithms, inter-process communication, and memory allocation methods. It provides step-by-step instructions for installing Ubuntu and Windows 10, as well as basic UNIX commands and shell programming. The manual serves as a comprehensive guide for students to explore and implement various operating system concepts and techniques.

Uploaded by

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

JPCOE OPERATING SYSTEMS LAB MANUAL

DEPARTMENT OF INFORMATION TECHNOLOGY

LIST OF EXPERIMENTS

S. Date of Date of Page Faculty


Name of the Experiment
No. Experiment Submission No Signature

1 Perform a case study by installing


and exploring various types of
operating systems on a physical or
logical (virtual) machine. (Linux
and Windows Installation).
2 a Illustration of UNIX commands

2 b Illustration of Shell Programming


3 Process Management using System
Calls : Fork, Exit, Getpid, Wait,
Close

4 Implement of various CPU


Scheduling Algorithms

5 Illustration of inter process


communication strategy

6 Implement mutual exclusion by


Semaphore

7 Write C programs to avoid


Deadlock using Banker's
Algorithm

8 Write a C program to Implement


Deadlock Detection Algorithm

9 Write C program to implement


Threading

10 Implement the paging Technique


using C program

11 Write C programs to implement the


following Memory Allocation
Methods

Page 1
JPCOE OPERATING SYSTEMS LAB MANUAL
E a. First Fit b. Worst Fit c. Best Fit

12 Write C programs to implement the


various Page Replacement
Algorithms

13 Write C programs to Implement the


various File Organization
Techniques

14 Implement the following File


Allocation Strategies using C
programs
a. Sequential b. Indexed c. Linked

15 Write C programs for the


implementation of various disk
scheduling algorithms

Page 1
JPCOE OPERATING SYSTEMS LAB MANUAL
E
PROGRAM 1 a) (CASE STUDY): Perform a case study by installing and exploring various types of
operating systems on a physical or logical (virtual) machine. (Linux Installation).
Instructions to Install Ubuntu Linux 12.04 (LTS) along with Windows
Back Up Your Existing Data!
This is highly recommended that you should take backup of your entire data before start
with the installation process.
Obtaining System Installation Media
Download latest Desktop version of Ubuntu from this link:
http://www.ubuntu.com/download/desktop
Booting the Installation System
There are several ways to boot the installation system. Some of the very popular ways are ,
Booting from a CD ROM, Booting from a USB memory stick, and Booting from TFTP.
Here we will learn how to boot installation system using a CD ROM.
Before booting the installation system, one need to change the boot order and set CD-ROM
as first boot device.
Changing the Boot Order of a Computers
As your computer starts, press the DEL, ESC, F1, F2, F8 or F10 during the initial startup screen.
Depending on the BIOS manufacturer, a menu may appear. However, consult the hardware
documentation for the exact key strokes. In my machine, its DEL key as shown in following screen-
shot.

2. Find the Boot option in the setup utility. Its location depends on your BIOS.
Select the Boot option from the menu, you can now see the options Hard Drive, CD-ROM
Drive, Removable Devices Disk etc.

Page 1
MCET OPERATING SYSTEMS LAB MANUAL

3. Change the boot sequence setting so that the CD-ROM is first. See the list of “Item Specific
Help” in right side of the window and find keys which is used to toggle to change the boot
sequence.

4. Insert the Ubuntu Disk in CD/DVD drive.


5. Save your changes. Instructions on the screen tell you how to save the changes on your
computer. The computer will restart with the changed settings.
Machine should boot from CD ROM, Wait for the CD to load...

In a few minutes installation wizard will be started. Select your language and click the
"Install Ubuntu" button to continue...

Page 2
JPCOE OPERATING SYSTEMS LAB MANUAL

Optionally, you can choose to download updates while installing and/or install third party
software, such as MP3 support. Be aware, though, that if you select those options, the entire
installation process will be longer!

Since we are going to create partitions manually, select Something else, then click
Continue. Keep in mind that even if you do not want to create partitions manually, it is better to
select the same option as indicated here. This would insure that the installer will not overwrite your
Windows , which will destroy your data. The assumption here is that sdb will be used just for
Ubuntu 12.04, and that there are no valuable data on it.

Page 3
JPCOE OPERATING SYSTEMS LAB MANUAL

Where are you? Select your location and Click the "Continue" button.

Keyboard layout
Select your keyboard layout and UK (English) and Click on “Continue” button.

Who are you?


Fill in the fields with your real name, the name of the computer (automatically generated,
but can be overwritten), username, and the password.
Also at this step, there's an option called "Log in automatically." If you check it, you will
automatically be logged in to the Ubuntu desktop without giving the password.
Option "Encrypt my home folder," will encrypt your home folder. Click on the "Continue"
button to continue...

Page 4
JPCOE OPERATING SYSTEMS LAB MANUAL

Now Ubuntu 12.04 LTS (Precise Pangolin) operating system will be installed.

It will take approximately 10-12 minutes (depending on computer's speed), a pop-up


window will appear, notifying you that the installation is complete, and you'll need to restart the
computer in order to use the newly installed Ubuntu operating system. Click the "Restart Now"
button.

Page 5
JPCOE OPERATING SYSTEMS LAB MANUAL

Please remove the CD and press the "Enter" key to reboot. The computer will be restarted.
In a few seconds, you should see Windows 7′s boot menu with two entires listed – Windows 7 and
Ubuntu 12.04 (LTS).
Then you may choose to boot into Windows 7 or Ubuntu 12.04 using the UP/Down arrow key.

Please select Ubuntu 12.04 (LTS) and press Enter to boot the machine in Ubuntu 12.04
Linux.

Page 6
JPCOE OPERATING SYSTEMS LAB MANUAL

Here you can see the users on the machine, Click on the user name and enter the password and
press Enter key to login.

We have successfully install and login to Ubuntu 12.04 LTS.


JPCOE OPERATING SYSTEMS LAB MANUAL

PROGRAM 1 b)(CASE STUDY): Perform a case study by installing and exploring various types of
operating systems on a physical or logical (virtual) machine. (Windows Installation).
Procedure:

Follow the steps below to proceed with the Windows 10 installation.


1. Select the following Language, Time, and Keyboard Layout and select“Next”.

2. Select “Install now” option.


JPCOE OPERATING SYSTEMS LAB MANUAL
3. Enter the product key to activate Windows and press “Next”, or press“Skip” to enter a valid
product key later.

4. Check the box next to “I accept the license terms” and select “Next”.

5. Choose the type of installation to perform.


- To upgrade to Windows 10 from an earlier version of Windows, select the “Upgrade”
option below.
- To perform a clean OS installation, select “Custom: Install Windows only (advanced)”option
below. For instructional purposes, this option was selected below.
JPCOE OPERATING SYSTEMS LAB MANUAL
6. Select the “Load driver” option to load the appropriate driver for the storagedevice.

7. Make sure to load the appropriate storage device driver onto a CD, DVD,or USB flash
drive before completing the next step.
- For storages devices attached to the Intel storage controller, load the Intel Rapid
Storage Technology enterprise (RSTe) driver.

o Select “Browse”, and browse to the CD, DVD, or USB flash drive to where
thestorage device driver is located and select “OK”.

-
JPCOE OPERATING SYSTEMS LAB MANUAL
- For storages devices attached to the Broadcom controller, load the Broadcom
storagedriver.

o Select “Browse”, browse to the CD, DVD, or USB flash drive to where
thestorage device driver is located and select “OK”.

8. Select the driver to install.


JPCOE OPERATING SYSTEMS LAB MANUAL
9. Select the drive to install Windows and select “Next” at the bottom.

10. Installing Windows screen.

11. After the installation completes, the system will automatically reboot. If noproduct key

was entered above, then it’ll prompt to enter a product key again. Either enter the
product key here and select “Next” or select “Do this later” at the bottom left.
JPCOE OPERATING SYSTEMS LAB MANUAL
12. Select “Use Express Settings” at the bottom right to use the default settings
or select “Customize settings” at the bottom left. For instructional
purposes, “Use Express settings” was selected.

13. Create an account by typing a “User name”. Optionally, type a password to


make it secure.

14. Windows 10 desktop screen.


JPCOE OPERATING SYSTEMS LAB MANUAL
15. At this point, download and install the appropriate device drivers,
i.e. IntelChipset, Intel AMT, Ethernet, Graphics, etc.
16. Restart the system after installation.

Page 14
JPCOE OPERATING SYSTEMS LAB MANUAL
Ex.No: 2 Illustrate UNIX commands and Shell Programming
2 a. BASIC UNIX COMMANDS
Aim : To illustrate basic UNIX commands

COMMAND
1. Date Command:
This command is used to display the current data and time.
Syntax :
$date
$date +%ch
Options :
a = Abbrevated
weekday. A = Full
weekday.
b = Abbrevated
month. B = Full
month.
c = Current day and time.
C = Display the century as a decimal
number. d = Day of the month.
D = Day in „mm/dd/yy‟
format h = Abbrevated month
day.
H = Display the
hour. L = Day of
the year.
m = Month of the
year. M = Minute.
P = Display AM or PM
S = Seconds
T = HH:MM:SS
format u = Week of
the year.
y = Display the year in 2 digit.
Y = Display the full year.
Z = Time zone .
To change the format :
Syntax :
$date “+%H-%M-%S‟
Page 15
JPCOE OPERATING SYSTEMS LAB MANUAL

2. Calender Command:
This command is used to display the calendar of the year or the particular month of calendar year.
Syntax :
a. $cal <year>
b. $cal <month> <year>
Here the first syntax gives the entire calendar for given year & the second Syntax gives the
calendar of reserved month of that year.

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

7. ’Binary’ Calculator Command:


It will change the „$ mode and in the new mode, arithmetic operations such as +,-
,*,/,%,n,sqrt(),length(),=, etc can be performed . This command is used to go to the binary calculus
mode.
Syntax:
$bc operations

Page 16
JPCOE OPERATING SYSTEMS LAB MANUAL
^d
$
1 base –inputbase
0 base – outputbase are used for base conversions.
Base :
Decimal = 1 Binary = 2 Octal = 8 Hexa = 16
8. ’CLEAR’ Command:
It is used to clear the screen.
Syntax : $clear
9. ’MAN’ Command:
It helps us to know about the particular command and its options & working. It is like
“help‟ command in windows.
Syntax : $man <command name>
10. MANIPULATION Command:
It is used to manipulate the screen.
Syntax : $tput <argument>
Arguments :
1. Clear – to clear the screen.
2. Longname – Display the complete name of the terminal.
3. SMSO – background become white and foreground become black color.
4. rmso – background become black and foreground becomes white color.
11. LIST Command:
It is used to list all the contents in the current working
directory. Syntax: $ ls –options <arguments>
If the command does not contain any argument means it is working in the Current
directory.
Options:
a– used to list all the files including the hidden
files. c– list all the files columnwise.
d- list all the directories.
m- list the files separated by commas.
p- list files include “/” to all the
directories. r- list the files in reverse
alphabetical order.
f- list the files based on the list modification
date. x-list in column wise sorted order.

Page 17
JPCOE OPERATING SYSTEMS LAB MANUAL
DIRECTORY RELATED COMMANDS
1. Present Working Directory Command :
To print the complete path of the current working directory.
Syntax : $pwd
2. MKDIR Command :
To create or make a new directory in a current directory.
Syntax : $mkdir <directory name>
3. CD Command :
To change or move the directory to the mentioned directory.
Syntax : $cd <directory name.
4. RMDIR Command :
To remove a directory in the current directory & not the current directory itself.
Syntax : $rmdir <directory name>

FILE RELATED COMMANDS


1. CREATE A FILE:
To create a new file in the current directory we use CAT command.
Syntax :
$cat > filename
The > symbol is redirectory we use cat command.
2. DISPLAY A FILE:
To display the content of file mentioned we use CAT command without “>” operator.
Syntax :
$cat filename
3. COPYING CONTENTS:
To copy the content of one file with another. If file doesnot exist, a new file is created and if the
file exists with some data then it is overwritten.
Syntax :
$ cat <filename source> >> <destination filename>
$ cat <source filename> >> <destination filename> it is avoid overwriting.
Options : -
-n content of file with numbers included with blank lines.
Syntax :
$cat –n <filename>
4. SORTING A FILE:
To sort the contents in alphabetical order in reverse order.
Syntax :
$sort <filename >

Page 18
JPCOE OPERATING SYSTEMS LAB MANUAL
5. COPYING CONTENTS FROM ONE FILE TO ANOTHER:
To copy the contents from source to destination file. So that both contents are
same. Syntax :
$cp <source filename> <destination filename>
6. MOVE Command:
To completely move the contents from source file to destination file and to remove the source file.
Syntax :
$ mv <source filename> <destination filename>
7. REMOVE Command:
To permanently remove the file we use this command.
Syntax :
$rm <filename>
8. WORD Command:
To list the content count of no of lines, words, characters.
Syntax :
$wc
<filename> Options :
-c – to display no of characters.
-l – to display only the lines.
-w – to display the no of words.
9. LINE PRINTER:
To print the line through the printer, we use lp command.
Syntax :
$lp <filename>
10. PAGE Command:
This command is used to display the contents of the file page wise & next page can be viewed by
pressing the enter key.
Syntax :
$pg <filename>

11. FILTERS AND PIPES


HEAD: It is used to display the top ten lines of file.
Syntax: $head<filename>
TAIL: This command is used to display the last ten lines of file.
Syntax: $tail<filename>
PAGE: This command shows the page by page a screen full of information is displayed after which the
page command displays a prompt and passes for the user to strike the enter key to continue scrolling.
Syntax: $ls –a\p
MORE: It also displays the file page by page .To continue scrolling with more command, press the space

Page 19
JPCOE OPERATING SYSTEMS LAB MANUAL
bar key.
Syntax: $more<filename>
GREP: This command is used to search and print the specified patterns from the file.
Syntax: $grep [option] pattern <filename>
SORT: This command is used to sort the data in some order.
Syntax: $sort<filename>
PIPE: It is a mechanism by which the output of one command can be channeled into the input of another
command.
Syntax: $who | wc -l
TR: The tr filter is used to translate one set of characters from the standard inputs to another.
Syntax: $tr “[a-z]” “[A-Z]”
COMMUNICATION THROUGH UNIX COMMANDS
1. MESG
Description: The message command is used to give permission to other users to send message to your
terminal.
Syntax: $mesg y
2. Command: WRITE
Description: This command is used to communicate with other users, who are logged in at the same time.
Syntax: $write <user name>
3. Command: WALL
Description: This command sends message to all users those who are logged in using the unix server.
Syntax: $wall <message>
4. Command: MAIL
Description: It refers to textual information, which can be transferred from one user to another
Syntax: $mail <user name>
5. Command: REPLY
Description: It is used to send reply to specified user.
Syntax: $reply<user name>

Page 20
JPCOE OPERATING SYSTEMS LAB MANUAL

2 b . SHELL PROGRAMMING
1. Shell or the Command interpreter is the mediator which interprets the commands and then
conveys them to the kernel which ultimately executes them.
2. Kernel is usually stored in a file called ‘UNIX’ where as the shell program in a file called
‘sh’.
3. Types of shells:-.
i. Bourne shell (sh) or Bourne again shell (bash)
ii. C shell (csh)
iii. Korn shell (ksh)
4. A shell program is nothing but a series of unix commands.
5. Instead of specifying one job at a time, the shell is given a to-do-list – a program – that
carries out an entire procedure.
6. Such programs are known as shell scripts.
Shell programming language incorporates most of the features that most modern day
programming languages offer.
Shell variables –
Rules for building shell variables are as follows:
1) A variable name is any combination of alphabets, digits and an underscore (‘_’).
2) No commas or blanks are allowed within a variable name.
3) The first character of a variable name must either be an alphabet or an underscore.
4) Variable names should be of any reasonable length.
5) Variable names are case sensitive.
Keywords for accepting input – read
Displaying output - echo
Assigning value to variables –
Values can be assigned to variables through read statement or also by using a simple
assignment operator. For ex: age=30
Note : While assigning values to variables using assignment operator, no spaces to be given on
either side of it. If the variable doesn’t exist it will be created and value assigned
1. Unix-defined variables or System variables or Environment variables
2. User- defined variables
Note : To print or access value of a variable use ‘$’ .
For ex: To print value of variable ‘flag‘ write - echo $flag
Arithmetic in Shell script -
1. All shell variables are string variables, hence to carry out arithmetic operations use expr

Page 21
JPCOE OPERATING SYSTEMS LAB MANUAL

command which evaluates arithmetic expressions.


2. More than one assignment can be done in a single statement.
3. Before and at the end of expr keyword use ` (back quote) sign not the (single quote i.e. ')
sign which is generally above TAB key.
4. Terms of the expression provided to expr must be separated by blanks. Thus expression
expr 10+20 is invalid.
5. The ‘*” symbol must be preceded by a \ ,otherwise the shell treats it as a wildcard
character for all files in the current directory
OPERATORS USED IN SHELL SCRIPT –
OPERATOR MEANING
–gt Greater than
–lt Less than
–ge Greater than or equal to
–le Less than or equal to
–ne Not equal to
–eq Equal to
–a Logical AND
–o Logical OR
! Logical NOT
CONTROL INSTRUCTIONS IN SHELLS -
There are four types of control instructions in shell :
• Sequence Control Instruction.
• Selection or Decision control Instruction
• Repetition or Loop control Instruction
• Case Control Instruction
Decision statements –
If-then-else-fi statements:
if condition then Commands else Commands fi
1) For statements :
for control variable in value1 value 2 value3 do
Command list done
2) While statements : while control command do
Command list Done
3) Until statements:
until control command do

Page 22
JPCOE OPERATING SYSTEMS LAB MANUAL

Command list done


Case statements:-
case value in
choice 1) commands;
choice 2) commands;
esac.

Steps to write and execute a script


1. Open the terminal. Go to the directory where you want to create your script.
2. Create a file with . sh extension.
3. Write the script in the file using an editor.
4. Make the script executable with command chmod +x <fileName>.
5. Run the script using ./<fileName>.

Page 23
JPCOE OPERATING SYSTEMS LAB MANUAL

2 B i)Concatenate two strings.

AIM:To write a shell program to concatenate two strings.


ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.

Step 3: Read the first string.

Step 4: Read the second string.


Step 5: Concatenate the two strings.
Step 6: Enter into the escape mode for the execution of the result and verify the output.
Step 7: Stop the program.
SOURCE CODE
echo “enter the first string”
read str1
echo “enter the second string”
read str2
echo “the concatenated string is” $str1$str2

OUTPUT:
$ vi concat.sh
$ sh concat.sh
Enter first string: Hello
Enter first string: World
The concatenated string is HelloWorld

RESULT:
Thus the shell program to concatenate two strings is executed and output is verified
successfully.

Page 24
JPCOE OPERATING SYSTEMS LAB MANUAL

2. b ii)Comparison of Two Strings

AIM:To write a shell program to compare the two strings.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.
Step 3: Read the first string.
Step 4: Read the second string.
Step 5: Compare the two strings using the if loop.
Step 6: If the condition satisfies then print that two strings are equal else print two strings are not
equal.
Step 7: Enter into the escape mode for the execution of the result and verify the output.
Step 8: Stop the program.

SOURCE CODE:
echo "enter a string 1"
read first
echo "enter a string 2"
read second
if [ $first = $second ] # this “ =” for other than digits equals
then
echo “strings are equal”
else
echo “strings are unequal”
fi

OUTPUT:
$ vi compare1.sh
$ sh compare1.sh
enter a string 1
abcxyz
enter a string 2
Page 25
JPCOE
abcxyz OPERATING SYSTEMS LAB MANUAL

Page 26
JPCOE OPERATING SYSTEMS LAB MANUAL

strings are equal


OUTPUT:
$ vi compare1.sh
$ sh compare1.sh
enter a string 1
hai
enter a string 2
cse
strings are unequal

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

Page 27
JPCOE OPERATING SYSTEMS LAB MANUAL

2 B iii)Comparison Of Two Strings From Command Lines

AIM:To write a shell program to compare of two strings from command lines.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.
Step 3: Read the first string.
Step 4: Read the second string.
Step 5: Compare the two strings using the if loop.
Step 6: If the condition satisfies then print that two strings are equal else print two strings are not
equal.
Step 7: Enter into the escape mode for the execution of the result and verify the output.
Step 8: Stop the program.

SOURCE CODE:
if [ $1 = $2 ]
then
echo "Strings are equal….."
else
echo "Strings are not equal….."
fi

OUTPUT:
$ vi compare2.sh
$ sh compare2.sh methodist methodist
Strings are equal…..
$ sh compare2.sh methodist tsidohtem
Strings are not equal…..

RESULT:
Thus the shell program to compare the two strings from command lines is executed and
output is verified successfully.

Page 28
JPCOE OPERATING SYSTEMS LAB MANUAL

• 2. B iv)Generate Fibonacci Series

AIM:To write a shell program to generate fibonacci series.

ALGORITHM:
Step 1: Start the program.
Step 2: Initialise a to 0 and b to 1.
Step 3: Print the values of ‘a’ and ‘b’.
Step 4: Add the values of ‘a'’ and ‘b’. Store the added value in variable 'c'.
Step 5: Print the value of ‘c’.
Step 6: Initialise ‘a’ to ‘b’ and ‘b’ to ‘c’.
Step 7: Repeat the steps 3, 4, 5 till the value of ‘a’ is less than 10.
Step 8: Stop the program.

SOURCE CODE:
echo “enter the no. of numbers in the series”
read n
a=0
b=1
d=2
echo “$a”
echo “$b”
while [ $d -lt $n ]
do
c=`expr $a + $b`
echo “$c”
a=$b
b=$c
d=`expr $d + 1`
done

Page 29
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:
$ vi fibonacci.sh
$ sh fibonacci.sh
enter the no. of numbers in the series
10
0
1
1
2
3
5
8
13
21
34

RESULT:
Thus the shell program to find the fibonacci series is executed and output is verified
successfully.

Page 30
JPCOE OPERATING SYSTEMS LAB MANUAL

• 2. B .v) Even or Odd Number

AIM:To write a shell program to find even or odd number.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.
Step 3: Read the number.
Step 4: Evaluate whether the given number Even or Odd.
Step 5: Print the Result and verify the output.
Step 6: Stop the program.

SOURCE CODE:
echo “enter the number”
read n
r=1
r=`expr $n % 2`
if [ $r -eq 0 ] # “-eq” for digits or numbers
then
echo “even”
else
echo “odd”
fi

OUTPUT:
$ vi evenodd.sh
$ sh evenodd.sh
enter the number
5
odd

RESULT:
Thus the shell program to find whether the given number is even or odd number is executed
and output is verified successfully.

Page 31
JPCOE OPERATING SYSTEMS LAB MANUAL

2. B. vi)List of Even Numbers in a Given Limit

AIM:To write a shell program to list of even numbers in a given limit.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.
Step 3: Read the limit.
Step 4: Read the second string.
Step 5: Evaluate all Even in the given limit.
Step 6: Print the Result and verify the output.
Step 7: Stop the program.

SOURCE CODE:
echo -n "enter the limit:"
x=2
read num
while [ $x -lt $num ]
do
echo -n "$x \t"
x=`expr $x + 2`
done

OUTPUT:

Page 32
JPCOE OPERATING SYSTEMS LAB MANUAL

$ vi evennums.sh
$ sh evennums.sh
enter the limit:20
2 4 6 8 10 12 14 16 18

RESULT:
Thus the shell program to find list of even numbers in a given limit is executed and output is verified successfully.

Page 33
JPCOE OPERATING SYSTEMS LAB MANUAL

Ex.No : 3 Process Management using System Calls : Fork, Exit, Getpid, Wait, Close
AIM : Write a C programs to implement UNIX system calls.

System Calls:

The interface between a process and an operating system is provided by system calls. In general,
system calls are available as assembly language instructions. They are also included in the manuals
used by the assembly level programmers. System calls are usually made when a process in user mode
requires access to a resource. Then it requests the kernel to provide the resource via a system call.

A figure representing the execution of the system call is given as follows −

As can be seen from this diagram, the processes execute normally in the user mode until a
system call interrupts this. Then the system call is executed on a priority basis in the kernel mode.
After the execution of the system call, the control returns to the user mode and execution of user
processes can be resumed.

In general, system calls are required in the following situations −

 If a file system requires the creation or deletion of files. Reading and writing from files also
require a system call.

 Creation and management of new processes.

 Network connections also require system calls. This includes sending and receiving packets.

 Access to a hardware devices such as a printer, scanner etc. requires a system call.

Page 34
JPCOE OPERATING SYSTEMS LAB MANUAL

Types of System Calls

There are mainly five types of system calls. These are explained in detail as follows −

Process Control

These system calls deal with processes such as process creation, process termination etc.

File Management

These system calls are responsible for file manipulation such as creating a file, reading a
file, writing into a file etc.

Device Management

These system calls are responsible for device manipulation such as reading from device
buffers, writing into device buffers etc.

Information Maintenance

These system calls handle information and its transfer between the operating system and the
user program.

Communication

These system calls are useful for interprocess communication. They also deal with creating
and deleting a communication connection.

Some of the examples of all the above types of system calls in Windows and Unix are given
as follows −

Types of System Calls Windows Linux

CreateProcess() fork()
Process Control ExitProcess() exit()
WaitForSingleObject() wait()

CreateFile() open()
ReadFile() read()
File Management
WriteFile() write()
CloseHandle() close()

Device Management SetConsoleMode() ioctl()


ReadConsole() read()

Page 35
JPCOE OPERATING SYSTEMS LAB MANUAL

Types of System Calls Windows Linux

WriteConsole() write()

GetCurrentProcessID() getpid()
Information Maintenance SetTimer() alarm()
Sleep() sleep()

CreatePipe() pipe()
Communication CreateFileMapping() shmget()
MapViewOfFile() mmap()

1.A) Fork() System Call:


AIM:To write the program to implement fork () system call.
DESCRIPTION:
Used to create new processes. The new process consists of a copy of the address space of the
original process. The value of process id for the child process is zero, whereas the value of process
id for the parent is an integer value greater than zero.
Syntax:
Fork ( );

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the variables pid and child id.
Step 3: Get the child id value using system call fork().
Step 4: If child id value is greater than zero then print as “i am in the parent process”.
Step 5: If child id! = 0 then using getpid() system call get the process id.
Step 6: Print “i am in the parent process” and print the process id.
Step 7: If child id! = 0 then using getppid() system call get the parent process id.
Step 8: Print “i am in the parent process” and print the parent process id.
Step 9: Else If child id value is less than zero then print as “i am in the child process”.
Step 10: If child id! = 0 then using getpid() system call get the process id.
Step 11: Print “i am in the child process” and print the process id.
Step 12: If child id! = 0 then using getppid() system call get the parent process id.
Step 13: Print “i am in the child process” and print the parent process id.
Step 14: Stop the program.

Page 36
JPCOE OPERATING SYSTEMS LAB MANUAL

PROGRAM :
SOURCE CODE:

/* fork system call */


#include<stdio.h>
#include <unistd.h>
#include<sys/types.h>
int main()
{
int id,childid;
id=getpid();
if((childid=fork())>0)
{
printf("\n i am in the parent process %d",id);
printf("\n i am in the parent process %d",getpid());
printf("\n i am in the parent process %d\n",getppid());
}
else
{
printf("\n i am in child process %d",id);
printf("\n i am in the child process %d",getpid());
printf("\n i am in the child process %d",getppid());
}
}

OUTPUT:
$ vi fork.c
$ cc fork.c
$ ./a.out
i am in child process 3765
i am in the child process 3766
i am in the child process 3765
i am in the parent process 3765
i am in the parent process 3765
i am in the parent process 3680
RESULT:

Page 37
JPCOE OPERATING
Thus the program was executed and verified successfully. SYSTEMS LAB MANUAL

Page 38
JPCOE OPERATING SYSTEMS LAB MANUAL

1.B) Wait () and Exit () System Calls:

AIM:To write the program to implement the system calls wait ( ) and exit ( ).
DESCRIPTION:
i. fork ( )
Used to create new process. The new process consists of a copy of the address space of the
original process. The value of process id for the child process is zero, whereas the value of process
id for the parent is an integer value greater than zero.
Syntax: fork ( );
ii. wait ( )
The parent waits for the child process to complete using the wait system call. The wait system
call returns the process identifier of a terminated child, so that the parent can tell which of its
possibly many children has terminated.
Syntax: wait (NULL);
iii. exit ( )
A process terminates when it finishes executing its final statement and asks the operating
system to delete it by using the exit system call. At that point, the process may return data (output)
to its parent process (via the wait system call).
Syntax: exit (0);
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the variables pid and i as integers.
Step 3: Get the child id value using the system call fork ().
Step 4: If child id value is less than zero then print “fork failed”.
Step 5: Else if child id value is equal to zero, it is the id value of the child and then start the child
process to execute and perform Steps 7 & 8.
Step 6: Else perform Step 9.
Step 7: Use a for loop for almost five child processes to be called.
Step 8: After execution of the for loop then print “child process ends”.
Step 9: Execute the system call wait ( ) to make the parent to wait for the child process to get over.
Step 10: Once the child processes are terminated, the parent terminates and hence prints “Parent
process ends”.
Step 11: After both the parent and the child processes get terminated it execute the wait ( ) system
call to permanently get deleted from the OS.
Step 12: Stop the program.

Page 39
JPCOE OPERATING SYSTEMS LAB MANUAL

PROGRAM:

1.B.1) SOURCE CODE:


#include<stdio.h>
#include<unistd.h>
int main( )
{
int i, pid;
pid=fork( );
if(pid== -1)
{
printf("fork failed");
exit(0);
}
else if(pid==0)
{
printf("\n Child process starts");
for(i=0; i<5; i++)
{
printf("\n Child process %d is called", i);
}
printf("\n Child process ends");
}
else
{
wait(0);
printf("\n Parent process ends");
}
exit(0);
}

Page 40
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:
$ vi waitexit.c
$ cc waitexit.c
$ ./a.out
Child process starts
Child process 0 is called
Child process 1 is called
Child process 2 is called
Child process 3 is called
Child process 4 is called
Child process ends
Parent process ends

RESULT:
Thus the program was executed and verified successfully

Page 41
JPCOE OPERATING SYSTEMS LAB MANUAL

1.B.2) WAIT () AND EXIT () SYSTEM CALLS


PROGRAM:
SOURCE CODE:
/* wait system call */
#include <stdlib.h>
#include <errno.h>
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
main()
{
pid_t pid;
int rv;
switch(pid=fork())
{
case -1:
perror("fork");
exit(1);
case 0:
printf("\n CHILD: This is the child process!\n");
fflush(stdout);
printf("\n CHILD: My PID is %d\n", getpid());
printf("\n CHILD: My parent's PID is %d\n",getppid());
printf("\n CHILD: Enter my exit status (make it small):\n ");
printf("\n CHILD: I'm outta here!\n");
scanf(" %d", &rv);
exit(rv);
default:
printf("\nPARENT: This is the parent process!\n");
printf("\nPARENT: My PID is %d\n", getpid());
fflush(stdout);
wait(&rv);
fflush(stdout);
printf("\nPARENT: My child's PID is %d\n", pid);

Page 42
JPCOE OPERATING SYSTEMS LAB MANUAL

printf("\nPARENT: I'm now waiting for my child to exit()...\n");


fflush(stdout);
printf("\nPARENT: My child's exit status is:
%d\n",WEXITSTATUS(rv));
printf("\nPARENT: I'm outta here!\n");
}
}
OUTPUT:

$ vi wait.c
$ cc wait.c
$ ./a.out
CHILD: This is the child process!
CHILD: My PID is 3821
CHILD: My parent's PID is 3820
CHILD: Enter my exit status (make it small):
CHILD: I'm outta here!
PARENT: This is the parent process!
PARENT: My PID is 3820
10
PARENT: My child's PID is 3821
PARENT: I'm now waiting for my child to exit()...
PARENT: My child's exit status is: 10
PARENT: I'm outta here!

RESULT:
Thus the program was executed and verified successfully

Page 43
JPCOE OPERATING SYSTEMS LAB MANUAL

1. C) EXECL SYSTEM CALL

AIM: To write a program to implement the system call execl ( ).


DESCRIPTION:
In execl () system function takes the path of the executable binary file (i.e. /bin/ls) as the
first and second argument. Then, the arguments (i.e. -lh, /home) that you want to pass to the
executable followed by NULL. Then execl () system function runs the command and prints the
output. If any error occurs, then execl () returns -1. Otherwise, it returns nothing.
Syntax:
int execl (const char *path, const char *arg, .... , NULL);
ALGORITHM
Step 1: Start the program.
Step 2: Include the necessary header files.
Step 3: Print execution of exec system call for the ls Unix command.
Step 4: Execute the execl function using the appropriate syntax for the Unix command ls.
Step 5: The list of all files and directories of the system is displayed.
Step 6: Stop the program.
PROGRAM :
SOURCE CODE:
/* execl system call */
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
main()
{
printf(“Before execl \n”);
execl(“/bin/ls”,”ls”,(char*)0);
printf(“After Execl\n”);
}

Page 44
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:
$ vi execl.c
$ cc execl.c
$ ./a.out
Before execl
a1 aaa aaa.txt abc a.out b1 b2 comm.c db db1 demo2 dir1 direc.c execl.c f1.txt fflag.c
file1 file2 fork.c m1 m2 wait.c xyz

RESULT:
Thus the program was executed and verified successfully

Page 45
JPCOE OPERATING SYSTEMS LAB MANUAL

1.D) EXECV SYSTEM CALL


AIM: To write a program to implement the system call execv ( ).
DESCRIPTION:
In execl() function, the parameters of the executable file is passed to the function as different
arguments. With execv(), you can pass all the parameters in a NULL terminated array argv. The
first element of the array should be the path of the executable file. Otherwise, execv() function
works just as execl() function.
Syntax:int execv (const char *path, char *const argv[]);
ALGORITHM:
Step 1: Start the program.
Step 2: Include the necessary header files.
Step 3: Print execution of exec system call for the ls Unix command.
Step 4: Execute the execv function using the appropriate syntax for the Unix command ls.
Step 5: The list of all files and directories of the system is displayed.
Step 6: Stop the program.
PROGRAM :
SOURCE CODE:
/* execv system call */
#include<stdio.h>
#include<sys/types.h>
main(int argc,char *argv[])
{
printf("before execv\n");
execv("/bin/ls",argv);
printf("after execv\n");
}
OUTPUT:
$ vi execv.c
$ cc execv.c
$ ./a.out
before execv
a1 aaa aaa.txt abc a.out b1 b2 comm.c db db1 demo2 dir1 direc.c execl.c execv.c f1.txt
fflag.c file1 file2 fork.c m1 m2 wait.c xyz
RESULT:
Thus the program was executed and verified successfully.

Page 46
JPCOE OPERATING SYSTEMS LAB MANUAL

1.E )Directory Management (Directory Hierarchy):


AIM:To write the program to implement the system calls opendir ( ), readdir ( ),closedir ().
DESCRIPTION:
UNIX offers a number of system calls to handle a directory. The following are most
commonly used system calls.
SYSTEM CALLS USED:
i. opendir ( )
Open a directory.
Syntax:
DIR * opendir (const char * dirname);
opendir () takes dirname as the path name and returns a pointer to a DIR structure. On error
returns NULL.
ii. readdir ( )
Read a directory.
Syntax:
struct dirent * readdir (DIR *dp) ;
A directory maintains the inode number and filename for every file in its fold. This function
returns a pointer to a dirent structure consisting of inode number and filename. ‘dirent’ structure is
defined in <dirent.h> to provide at least two members – inode number and directory name.
struct dirent
{
ino_t d_ino; // directory inode number
char d_name[]; // directory name
}
iii. closedir ():
Close a directory.
Syntax:
int closedir (DIR * dp);
Closes a directory pointed by dp. It returns 0 on success and -1 on error.

Page 47
JPCOE OPERATING SYSTEMS LAB MANUAL

ALGORITHM:

Step 1: Start the program.


Step 2: In the main function pass the arguments.
Step 3: Create structure as stat buff and the variables as integer.
Step 4: Open the directory.
Step 5: Read the contents of the directory (filenames).
Step 6: Display the contents of the directory.
Step 7: Close the directory.
Step 4: Stop the program.
PROGRAM:
SOURCE CODE:
/* Recursively descend a directory hierarchy pointing a file */
#include<stdio.h>
#include<dirent.h>
#include<errno.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
struct dirent *direntp; DIR *dirp; if(argc!=2)
{
printf("ussage %s directory name \n",argv[0]);
return 1;

}
if((dirp=opendir(argv[1]))==NULL)
{
perror("Failed to open directory \n");
return 1;
}
while((direntp=readdir(dirp))!=NULL)
printf("%s\n",direntp->d_name);
while((closedir(dirp)==-1)&&(errno==EINTR));
return 0;
}

Page 48
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:
$ vi direc.c
$ cc direc.c
$ ./a.out ./
f1.txt
fflag.c
.
..
b2
comm.c
dir1
demo2
a1
m1
db
a.out
direc.c
db1
file1
b1
xyz
abc
aaa
file2
aaa.txt
m2

RESULT:
Thus the program was executed and verified successfully.

Page 49
JPCOE OPERATING SYSTEMS LAB MANUAL

1.F) File Management:

AIM:To write the program to implement the system calls open ( ), read ( ), write ( ) & close ().

DESCRIPTION:
The file structure related system calls available in the UNIX system let you create, open, and
close files, read and write files, randomly access files, alias and remove files, get information about
files, check the accessibility of files, change protections, owner, and group of files, and control
devices. These operations either use a character string that defines the absolute or relative path
name of a file, or a small integer called a file descriptor that identifies the I/O channel. A channel is
a connection between a process and a file that appears to the process as an unformatted stream of
bytes. The kernel presents and accepts data from the channel as a process reads and writes that
channel. To a process then, all input and output operations are synchronous and unbuffered.
SYSTEM CALLS USED:
System calls are functions that a programmer can call to perform the services of the operating
system.
Open ():
Open () system call to open a file.
open () returns a file descriptor, an integer specifying the position of this open n file in the
table of open files for the current process.
Close ():
Close () system call to close a file.
Read ():
Read () data from a file opened for reading.
Write ():
Write () data to a file opened for writing.
The open () system call:
#include<fcntl.h>
int open (const char *path, int oflag);
The return value is the descriptor of the file. Returns -1 if the file could not be opened. The
first parameter is path name of the file to be opened and the second parameter is the opening mode
specified by bitwise oring one or more of the following values

Page 50
JPCOE OPERATING SYSTEMS LAB MANUAL

Value Meaning
O_RDONLY Open for reading only
O_WRONLY Open for writing only
O_RDWR Open for reading and writing
O_APPEND Open at end of file for writing
O_CREAT Create the file if it doesn't already exist
O_EXCL If set and O_CREAT set will cause open() to fail if the file already exists
O_TRUNC Truncate file size to zero if it already exists

close () system call:


The close () system call is used to close files.
#include <unistd.h>
int close (int fildes);
It is always good practices to close files when not needed as open files do consume
resources and all normal systems impose a limit on the number of files that a process can hold open.
The read () system call:
The read () system call is used to read data from a file or other object identified by a file
descriptor. The prototype is
#include<sys/types.h>
size_t read (int fildes, void *buf, size_t nbyte);
fildes is the descriptor, buf is the base address of the memory area into which the data is
read and nbyte is the maximum amount of data to read. The return value is the actual amount of
data read from the file. The pointer is incremented by the amount of data read. An attempt to read
beyond the end of a file results in a return value of zero.
The write () system call:
The write () system call is used to write data to a file or other object identified by a file
descriptor. The prototype is
#include<sys/types.h>
size_t write (int fildes, const void *buf, size_t nbyte);

Page 51
JPCOE OPERATING SYSTEMS LAB MANUAL

ALGORITHM:
Step 1: Start the program.
Step 2: Declare the structure elements.
Step 3: Create a temporary file named temp1.
Step 4: Open the file named “test” in a write mode.
Step 5: Enter the strings for the file.
Step 6: Write those strings in the file named “test”.
Step 7: Create a temporary file named temp2.
Step 8: Open the file named “test” in a read mode.
Step 9: Read those strings present in the file “test” and save it in temp2.
Step 10: Print the strings which are read.
Step 11: Stop the program.
PROGRAM :
SOURCE CODE:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
int main( )
{
int fd[2];
char buf1[25]= ”just a test\n”; char
buf2[50];
fd[0]=open(“file1”, O_RDWR);
fd[1]=open(“file2”, O_RDWR);
write(fd[0], buf1, strlen(buf1));
printf(“\n Enter the text now….”);
gets(buf1);
write(fd[0], buf1, strlen(buf1));
lseek(fd[0], SEEK_SET, 0);
read(fd[0], buf2, sizeof(buf1));
write(fd[1], buf2, sizeof(buf2));
close(fd[0]);
close(fd[1]);
printf(“\n”);

Page 52
JPCOE OPERATING SYSTEMS LAB MANUAL

return0;
}
OUTPUT:
Enter the text now….progress
Cat file1 Just a
test progress
Cat file2 Just a test progress
RESULT:
Thus the program was executed successfully.

Page 53
JPCOE OPERATING SYSTEMS LAB MANUAL
4. AIM :Write C programs to simulate CPU scheduling algorithms: FCFS, SJF, and
Round Robin.
CPU Scheduling Algorithms:
Scheduling of processes/work is done to finish the work on time.
Below are different times with respect to a process.
Arrival Time : Time at which the process arrives in the ready queue.
Completion Time : Time at which process completes its execution.
Burst Time : Time required by a process for CPU execution.
Turn Around Time : Time Difference between completion time and arrival time.
Turn Around Time = Completion Time - Arrival Time
Waiting Time(W.T) : Time Difference between turn around time and burst time.
Waiting Time = Turn Around Time - Burst Time
Why do we need scheduling?
A typical process involves both I/O time and CPU time. In a uniprogramming system like MS-
DOS, time spent waiting for I/O is wasted and CPU is free during this time. In multiprogramming
systems, one process can use CPU while another is waiting for I/O. This is possible only with
process scheduling.
Objectives of Process Scheduling Algorithm
 Max CPU utilization [Keep CPU as busy as possible]
 Fair allocation of CPU.
 Max throughput [Number of processes that complete their execution per time unit]
 Min turnaround time [Time taken by a process to finish execution]
 Min waiting time [Time a process waits in ready queue]
 Min response time [Time when a process produces first response]
Different Scheduling Algorithms:
First Come First Serve (FCFS): Simplest scheduling algorithm that schedules according to arrival
times of processes. First come first serve scheduling algorithm process that requests the CPU first is
allocated the CPU first. It is implemented by using the 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. FCFS is a
non – preemptive scheduling algorithm.
Note: First come first serve suffers from convoy effect.
Shortest Job First (SJF): Process which has the shortest burst time is scheduled first. If two
processes have the same bust time then FCFS is used to break the tie. It is a non-preemptive
scheduling algorithm.

Page 54
JPCOE OPERATING SYSTEMS LAB MANUAL

Longest Job First (LJF): It is similar to SJF scheduling algorithm. But, in this scheduling
algorithm, we give priority to the process having the longest burst time. This is non – preemptive in
nature i.e., when any process starts executing, can’t be interrupted before complete execution.
Shortest Remaining Time First (SRTF): It is preemptive mode of SJF algorithm in which jobs are
schedule according to shortest remaining time.
Longest Remaining Time First (LRTF): It is preemptive mode of LJF algorithm in which we give
priority to the process having largest burst time remaining.
Round Robin Scheduling: Each process is assigned a fixed time (Time Quantum/Time Slice) in
cyclic way. It is designed especially for the time-sharing system. 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 Round Robin scheduling, we
keep the ready queue as a FIFO queue o£ 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. One of two things will then happen. The
process may have a CPU burst of less than 1-time quantum. In this case, the process itself will
release the CPU voluntarily. The scheduler will then proceed to the next process in the ready queue.
Otherwise, if the CPU burst of the currently running process is longer than 1-time quantum, the
timer will go off and will cause an interrupt to the operating system. A context switch will be
executed, and the process will be put at the tail o£ the ready queue. The CPU scheduler will then
select the next process in the ready queue.
Priority Based scheduling (Non - Preemptive): In this scheduling, processes are scheduled
according to their priorities, i.e., highest priority process is scheduled first. If priorities of two
processes match, then schedule according to arrival time. Here starvation of process is possible.
Highest Response Ratio Next (HRRN) In this scheduling, processes with highest response ratio is
scheduled. This algorithm avoids starvation.
Response Ratio = (Waiting Time + Burst time) / Burst time
Multilevel Queue Scheduling: According to the priority of process, processes are placed in the
different queues. Generally high priority process is placed in the top level queue. Only after
completion of processes from top level queue, lower level queued processes are scheduled. It can
suffer from starvation.
Multi level Feedback Queue Scheduling: It allows the process to move in between queues. The
idea is to separate processes according to the characteristics of their CPU bursts. If a process uses
too much CPU time, it is moved to a lower-priority queue.

Page 55
JPCOE OPERATING SYSTEMS LAB MANUAL

4.a) Write C program to simulate FCFS CPU scheduling algorithm.


AIM:To write a C program to implement FCFS CPU scheduling algorithm.
DESCRIPTION:
• Jobs are executed on FCFS (First Come, First Serve) basis.
• It is a non-preemptive, preemptive scheduling algorithm.
• Easy to understand and implement.
• Its implementation is based on FIFO (First In First Out) queue.
• Poor in performance as average wait time is high.

Wait time of each process is as follows –

Process Wait Time : Service Time - Arrival Time

P0 0-0=0

P1 5-1=4

P2 8-2=6

P3 16 - 3 = 13

Average Wait Time: (0+4+6+13) / 4 = 5.75

Page 56
JPCOE OPERATING SYSTEMS LAB MANUAL

ALGORITHM:
Step 1: Start the program.
Step 2: Create the number of process.
Step 3: Get the ID and Service time for each process.
Step 4: Initially, Waiting time of first process is zero and Total time for the first process is the
starting time of that process.
Step 5: Calculate the Total time and Processing time for the remaining processes.
Step 6: Waiting time of one process is the Total time of the previous process.
Step 7: Total time of process is calculated by adding Waiting time and Service time.
Step 8: Total waiting time is calculated by adding the waiting time for lack process.
Step 9: Total turn around time is calculated by adding all total time of each process.
Step 10: Calculate Average waiting time by dividing the total waiting time by total number of
process.
Step 11: Calculate Average turn around time by dividing the total time by the number of process.
Step 12: Display the result.
Step 13: Stop the program.
PROGRAM:
SOURCE CODE:
/* A program to simulate the FCFS CPU scheduling algorithm */
#include<stdio.h>
int main()
{
char pn[10][10];
int arr[10],bur[10],star[10],finish[10],tat[10],wt[10],i,n;
int totwt=0,tottat=0;
printf("Enter the number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Process Name, Arrival Time & Burst Time:");
scanf("%s%d%d",&pn[i],&arr[i],&bur[i]);
}
for(i=0;i<n;i++)
{

Page 57
JPCOE OPERATING SYSTEMS LAB MANUAL

if(i==0)
{
star[i]=arr[i];
wt[i]=star[i]-arr[i];
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
else
{
star[i]=finish[i-1];
wt[i]=star[i]-arr[i];
finish[i]=star[i]+bur[i];
tat[i]=finish[i]-arr[i];
}
}

printf("\nPName Arrtime Burtime Start TAT Finish");


for(i=0;i<n;i++)
{
printf("\n%s\t%6d\t\t%6d\t%6d\t%6d\t%6d",pn[i],arr[i],bur[i],star[i],tat[i],finish[i]);
totwt+=wt[i];
tottat+=tat[i];
}
printf("\nAverage Waiting time:%f", (float)totwt);
printf("\nAverage Turn Around Time:%f", (float)tottat);
}

Page 58
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:
$ vi fcfs.c
$ cc fcfs.c
$ ./a.out
Enter the number of processes: 3
Enter the Process Name, Arrival Time & Burst Time: 1 2 3
Enter the Process Name, Arrival Time & Burst Time: 2 5 6
Enter the Process Name, Arrival Time & Burst Time: 3 6 7
PName Arrtime Burtime Start TAT Finish
1 2 3 2 3 5
2 5 6 5 6 11
3 6 7 11 12 18
Average Waiting time: 1.666667
Average Turn Around Time: 7.000000

RESULT:
Thus the program was executed and verified successfully.

Page 59
JPCOE OPERATING SYSTEMS LAB MANUAL

4 bWrite C program to simulate SJF CPU scheduling algorithm.


AIM:To write a C program to implement SJF CPU scheduling algorithm.
DESCRIPTION:
• This is also known as shortest job first, or SJF
• This is a non-preemptive, pre-emptive scheduling algorithm.
• Best approach to minimize waiting time.
• Easy to implement in Batch systems where required CPU time is known in advance.
• Impossible to implement in interactive systems where required CPU time is not known.
• The processer should know in advance how much time process will take.
Given: Table of processes, and their Arrival time, Execution time

Process Arrival Time Execution Time Service Time

P0 0 5 0

P1 1 3 5

P2 2 8 14

P3 3 6 8

Waiting time of each process is as follows –

Process Waiting Time

P0 0-0=0

P1 5-1=4

P2 14 - 2 = 12

P3 8-3=5

Average Wait Time: (0 + 4 + 12 + 5)/4 = 21 / 4 = 5.25

Page 60
JPCOE OPERATING SYSTEMS LAB MANUAL

ALGORITHM:

Step 1: Start the program.


Step 2: Get the number of process.
Step 3: Get the id and service time for each process.
Step 4: Initially the waiting time of first short process as 0 and total time of first short is process the
service time of that process.
Step 5: Calculate the total time and waiting time of remaining process.
Step 6: Waiting time of one process is the total time of the previous process.
Step 7: Total time of process is calculated by adding the waiting time and service time of each
process.
Step 8: Total waiting time calculated by adding the waiting time of each process.
Step 9: Total turn around time calculated by adding all total time of each process.
Step 10: Calculate average waiting time by dividing the total waiting time by total number of
process.
Step 11: Calculate average turn around time by dividing the total waiting time by total number of
process.
Step 12: Display the result.
Step 13: Stop the program.

PROGRAM:

SOURCE CODE:
/* A program to simulate the SJF CPU scheduling algorithm */
#include<stdio.h>
#include<string.h>
main()
{
int i=0,pno[10],bt[10],n,wt[10],temp=0,j,tt[10];
float sum,at;
printf("\n Enter the no of process ");
scanf("\n %d",&n);
printf("\n Enter the burst time of each process");
for(i=0;i<n;i++)
{
printf("\n p%d",i);
scanf("%d",&bt[i]);

Page 61
JPCOE OPERATING SYSTEMS LAB MANUAL

}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(bt[i]>bt[j])
{
temp=bt[i];
bt[i]=bt[j];
bt[j]=temp;
temp=pno[i];
pno[i]=pno[j];
pno[j]=temp;
}
}
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=bt[i-1]+wt[i-1];
sum=sum+wt[i];
}
printf("\n process no \t burst time\t waiting time \t turn around time\n");
for(i=0;i<n;i++)
{
tt[i]=bt[i]+wt[i];
at+=tt[i];
printf("\n p%d\t\t%d\t\t%d\t\t%d",i,bt[i],wt[i],tt[i]);
}
printf("\n\n\t Average waiting time%f\n\t Average turn around time%f", sum, at);
}

Page 62
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:

$ vi sjf.c
$ cc sjf.c
$ ./a.out
Enter the no of process 5
Enter the burst time of each process
p0 1
p1 5
p2 2
p3 3
p4 4

process no burst time waiting time turn around time


p0 1 0 1
p1 2 1 3
p2 3 3 6
p3 4 6 10
p4 5 10 15

Average waiting time 4.000000


Average turn around time 7.000000
RESULT:
Thus the program was executed and verified successfully.

Page 63
JPCOE OPERATING SYSTEMS LAB MANUAL

4. c Write C program to simulate Round Robin CPU scheduling algorithm.


AIM:To write a C program to implement Round Robin CPU scheduling algorithm.
DESCRIPTION
• Round Robin is the preemptive process scheduling algorithm.
• Each process is provided a fix time to execute, it is called a quantum.
• Once a process is executed for a given time period, it is preempted
and other process executes for a given time period.
• Context switching is used to save states of preempted processes.

Wait time of each process is as follows –

Process Wait Time : Service Time - Arrival Time

P0 (0 - 0) + (12 - 3) = 9

P1 (3 - 1) = 2

P2 (6 - 2) + (14 - 9) + (20 - 17) = 12

P3 (9 - 3) + (17 - 12) = 11

Average Wait Time: (9+2+12+11) / 4 = 8.5

Page 64
JPCOE OPERATING SYSTEMS LAB MANUAL

ALGORITHM:
Step 1: Start the program.
Step 2: Initialize all the structure elements.
Step 3: Receive inputs from the user to fill process id, burst time and arrival time.
Step 4: Calculate the waiting time for all the process id.
i. The waiting time for first instance of a process is calculated as: a[i].waittime=count +
a[i].arrivt.
ii. The waiting time for the rest of the instances of the process is calculated as:
a) If the time quantum is greater than the remaining burst time then waiting time is
calculated as: a[i].waittime=count + tq.
b) Else if the time quantum is greater than the remaining burst time then waiting time is
calculated as: a[i].waittime=count - remaining burst time
Step 5: Calculate the average waiting time and average turnaround time
Step 6: Print the results of the step 4.
Step 7: Stop the program.
PROGRAM :
SOURCE CODE:
/* A program to simulate the Round Robin CPU scheduling algorithm */
#include<stdio.h>
struct process
{
int burst,wait,comp,f;
}p[20]={0,0};
int main()
{
int n,i,j,totalwait=0,totalturn=0,quantum,flag=1,time=0;
printf("\nEnter The No Of Process :");
scanf("%d",&n);
printf("\nEnter The Quantum time (in ms) :");
scanf("%d",&quantum);
for(i=0;i<n;i++)
{
printf("Enter The Burst Time (in ms) For Process #%2d :",i+1);
scanf("%d",&p[i].burst);

Page 65
JPCOE OPERATING SYSTEMS LAB MANUAL

p[i].f=1;
}
printf("\nOrder Of Execution \n");
printf("\nProcess Starting Ending Remaining");
printf("\n\t\tTime \tTime \t Time");
while(flag==1)
{
flag=0;
for(i=0;i<n;i++)
{
if(p[i].f==1)
{
flag=1;
j=quantum;
if((p[i].burst-p[i].comp)>quantum)
{
p[i].comp+=quantum;
}
else
{
p[i].wait=time-p[i].comp;
j=p[i].burst-p[i].comp;
p[i].comp=p[i].burst;
p[i].f=0;
}

printf("\nprocess # %-3d %-10d %-10d %-10d", i+1, time, time+j,


p[i].burst-p[i].comp);
time+=j;
}
}
}
printf("\n\n ");
printf("\nProcess \t Waiting Time TurnAround Time ");
for(i=0;i<n;i++)
{

Page 66
JPCOE OPERATING SYSTEMS LAB MANUAL

printf("\nProcess # %-12d%-15d%-15d",i+1,p[i].wait,p[i].wait+p[i].burst);
totalwait=totalwait+p[i].wait;
totalturn=totalturn+p[i].wait+p[i].burst;
}
printf("\n\nAverage\n------------------ ");
printf("\nWaiting Time: %fms",totalwait/(float)n);
printf("\nTurnAround Time : %fms\n\n",totalturn/(float)n);
return 0;
}

OUTPUT:

$ vi rr.c
$ cc rr.c
$ ./a.out
Enter The No Of Process: 3
Enter The Quantum time (in ms): 5
Enter The Burst Time (in ms) For Process # 1: 25
Enter The Burst Time (in ms) For Process # 2: 30
Enter The Burst Time (in ms) For Process # 3: 54
Order Of Execution
Process Starting Ending Remaining
Time Time Time
process # 1 0 5 20
process # 2 5 10 25
process # 3 10 15 49
process # 1 15 20 15
process # 2 20 25 20
process # 3 25 30 44
process # 1 30 35 10
process # 2 35 40 15
process # 3 40 45 39
process # 1 45 50 5
process # 2 50 55 10
process # 3 55 60 34
process # 1 60 65 0

Page 67
JPCOE OPERATING SYSTEMS LAB MANUAL

process # 2 65 70 5
process # 3 70 75 29
process # 2 75 80 0
process # 3 80 85 24
process # 3 85 90 19
process # 3 90 95 14
process # 3 95 100 9
process # 3 100 105 4
process # 3 105 109 0

Process Waiting Time TurnAround Time


Process # 1 40 65
Process # 2 50 80
Process # 3 55 109
Average

Waiting Time: 48.333333ms


TurnAround Time: 84.666667ms

RESULT:
Thus the program was executed and verified successfully.

68
JPCOE OPERATING SYSTEMS LAB MANUAL

5. AIM: Write C programs to simulate Intra & Inter – Process Communication (IPC)
techniques: Pipes, Messages Queues, and Shared Memory.
DESCRIPTION:
Inter Process Communication (IPC) is a mechanism that involves communication of one process
with another process. This usually occurs only in one system.
Communication can be of two types:
Between related processes initiating from only one process, such as parent and child processes.
Between unrelated processes, or two or more different processes.
Following are some important terms that we need to know before proceeding further on this topic.
Pipes − Communication between two related processes. The mechanism is half duplex meaning the
first process communicates with the second process. To achieve a full duplex i.e., for the second
process to communicate with the first process another pipe is required.
FIFO − Communication between two unrelated processes. FIFO is a full duplex, meaning the first
process can communicate with the second process and vice versa at the same time.
Message Queues − Communication between two or more processes with full duplex capacity. The
processes will communicate with each other by posting a message and retrieving it out of the queue.
Once retrieved, the message is no longer available in the queue.
Shared Memory − Communication between two or more processes is achieved through a shared
piece of memory among all processes. The shared memory needs to be protected from each other by
synchronizing access to all the processes.
Semaphores − Semaphores are meant for synchronizing access to multiple processes. When one
process wants to access the memory (for reading or writing), it needs to be locked (or protected) and
released when the access is removed. This needs to be repeated by all the processes to secure data.
Signals − Signal is a mechanism to communication between multiple processes by way of signaling.
This means a source process will send a signal (recognized by number) and the destination process
will handle it accordingly.
Note − Almost all the programs in this tutorial are based on system calls under Linux Operating
System (executed in Ubuntu).

69
JPCOE OPERATING SYSTEMS LAB MANUAL

PROGRAM 4.A ) ECHOSERVER USING PIPES


SOURCE CODE:
/* Implementation of echoserver using Pipes */
#include<stdio.h>
#include<string.h>
#define msgsize 29
int main()
{
int ser[2],cli[2],pid;
char inbuff[msgsize];
char *msg="Thank you";
system("clear");
pipe(ser);
pipe(cli);
printf("\n server read id =%d,write id=%d",ser[0],ser[1]);
printf("\n client read id =%d,write id=%d",cli[0],cli[1]);
pid=fork();
if(pid==0)
{
printf("\n i am in child process !");
close(cli[0]);
close(ser[1]);
write(cli[1],msg,msgsize);
printf("\n message written to pipe..!");
sleep(2);
read(ser[0],inbuff,msgsize);
printf("\n echo message received from server");
printf("\n %s",inbuff);
}
else
{
close(cli[1]);
close(ser[0]);
printf("\n parent process");
read(cli[0],inbuff,msgsize);

70
JPCOE OPERATING SYSTEMS LAB MANUAL

write(ser[1],inbuff,msgsize);
printf("\n parent ended!");
}
}

OUTPUT:

$ vi echopipe.c
$ cc echopipe.c
$ ./a.out

server read id =3,write id=4


client read id =5,write id=6
i am in child process !
client read id =5,write id=6
parent process
parent ended!

$ message written to pipe..!


echo message received from server

RESULT:
Thus the program was executed and verified successfully.

71
JPCOE OPERATING SYSTEMS LAB MANUAL

PROGRAM 4.B) ECHO SERVER USING MESSAGES


SOURCE CODE:
/* Implementation of echo server using messages */
#include<sys/ipc.h>
#include<stdio.h>
#include<string.h>
#include<sys/msg.h>
#include<stdlib.h>
struct
{
long mtype;
char mtext[20];
}send,recv;
main()
{
int qid,pid,len;
qid=msgget((key_t)0X2000,IPC_CREAT|0666);
if(qid==-1)
{
perror("\n message failed");
exit(1);
}
send.mtype=1;
strcpy(send.mtext,"\n hello i am parent");
len=strlen(send.mtext);
pid=fork();
if(pid>0)
{
if(msgsnd(qid,&send,len,0)==-1)
{
perror("\n message sending failed");
exit(1);
}
printf("\n message has been posted");
sleep(2);

72
JPCOE OPERATING SYSTEMS LAB MANUAL

if(msgrcv(qid,&recv,100,2,0)==-1)
{
perror("\n msgrcv error:");
exit(1);
}
printf("\n message received from child - %s\n",recv.mtext);
}
else
{
send.mtype=2;
strcpy(send.mtext,"\n hi i am child");
len=strlen(send.mtext);
if(msgrcv(qid,&recv,100,1,0)==-1)
{
perror("\n child message received failed");
exit(1);
}
if(msgsnd(qid,&send,len,0)==-1)
{
perror("\n child message send failed");
}
printf("\n received from parent - %s",recv.mtext);
}
}

OUTPUT:
$ vi echomsg.c
$ cc echomsg.c
$ ./a.out
received from parent -
hello i am parent message has been posted
message received from child -
hi i am child
RESULT:
Thus the program was executed and verified successfully.

73
JPCOE OPERATING SYSTEMS LAB MANUAL

6.AIM: Write C programs to simulate solutions to Classical Process Synchronization


Problems: Dining Philosophers, Producer – Consumer, Readers – Writers.
Process Synchronization
The basic concepts of synchronization have been presented, and several case studies have been
implemented as simulation models. The need for synchronization originates when processes need
to execute concurrently. The main purpose of synchronization is the sharing of resources without
interference using mutual exclusion. The other purpose is the coordination of the process
interactions in an operating system. Semaphores and monitors are the most powerful and most
commonly used mechanisms to solve synchronization problems. Most operating systems provide
semaphores. The producer-consumer problem (also known as the bounded-buffer problem), and
the readers-writers problem are two classical case studies considered to describe and test
synchronization mechanisms. These two problems are implemented in various simulation models,
each with a different solution or different workload parameters to study the process
synchronization mechanisms that can be used with interacting processes.
• Dining Philosophers Problem.
AIM:To write C programs to simulate solutions to Dining Philosophers Problem.
DESCRIPTION:
The dining – philosophers problem is considered a classic synchronization problem because
it is an example of a large class of concurrency – control problems. It is a simple representation of
the need to allocate several resources among several processes in a deadlock-free and starvation-
free manner. Consider five philosophers who spend their lives thinking and eating. The
philosophers share a circular table surrounded by five chairs, each belonging to one philosopher. In
the center of the table is a bowl of rice, and the table is laid with five single chopsticks. When a
philosopher thinks, she does not interact with her colleagues. From time to time, a philosopher gets
hungry and tries to pick up the two chopsticks that are closest to her (the chopsticks that are
between her and her left and right neighbours). A philosopher may pick up only one chopstick at a
time. Obviously, she cam1ot pick up a chopstick that is already in the hand of a neighbour. When a
hungry philosopher has both her chopsticks at the same time, she eats without releasing her
chopsticks. When she is finished eating, she puts down both of her chopsticks and starts thinking
again. The dining-philosophers problem may lead to a deadlock situation and hence some rules
have to be framed to avoid the occurrence of deadlock.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the number of philosophers.
Step 3: Declare one thread per philosopher.

74
JPCOE OPERATING SYSTEMS LAB MANUAL

Step 4: Declare one chopsticks per philosopher.


Step 5: When a philosopher is hungry.
i. See if chopsticks on both sides are free.
ii. Acquire both chopsticks or.
iii. Eat.
iv. restore the chopsticks.
v. If chopsticks aren’t free.
Step 6: Wait till they are available.
Step 7: Stop the program.
PROGRAM:
SOURCE CODE:
int tph, philname[20], status[20], howhung, hu[20], cho;
int main()
{
int i;
clrscr();
printf("\n\nDINING PHILOSOPHER PROBLEM");
printf("\nEnter the total no. of philosophers: ");
scanf("%d",&tph);
for(i=0;i<tph;i++)
{
philname[i] = (i+1);
status[i]=1;
}
printf("How many are hungry : ");
scanf("%d", &howhung);
if(howhung==tph)
{
printf("\nAll are hungry..\nDead lock stage will occur");
printf("\nExiting..");
}
else
{
for(i=0;i<howhung;i++)
{

75
JPCOE OPERATING SYSTEMS LAB MANUAL

printf("Enter philosopher %d position: ",(i+1));


scanf("%d", &hu[i]);
status[hu[i]]=2;
}
do
{
printf("1.One can eat at a time\t2.Two can eat at a time\t3.Exit\nEnter your
choice:");
scanf("%d", &cho);
switch (cho)
{
case 1: one();
break();
case 2: two();
break;
case 3: exit(0);
default: printf("\nInvalid option..");
}
}
while(1);
}
}
one()
{
int pos=0, x, i;
printf("\nAllow one philosopher to eat at any time\n");
for(i=0;i<howhung; i++, pos++)
{
printf("\nP %d is granted to eat", philname[hu[pos]]);
for(x=pos;x<howhung;x++)
printf("\nP %d is waiting", philname[hu[x]]);
}
}
two()
{

76
JPCOE OPERATING SYSTEMS LAB MANUAL

int i, j, s=0, t, r, x;
printf("\n Allow two philosophers to eat at same time\n");
for(i=0;i<howhung;i++)
{
for(j=i+1;j<howhung;j++)
{
if(abs(hu[i]-hu[j])>=1&& abs(hu[i]-hu[j])!=4)
{
printf("\n\ncombination %d \n", (s+1));
t=hu[i];
r=hu[j];
s++;
printf("\nP %d and P %d are granted to eat", philname[hu[i]],
philname[hu[j]]);
for(x=0;x<howhung;x++)
{
if((hu[x]!=t)&&(hu[x]!=r))
printf("\nP %d is waiting", philname[hu[x]]);
}
}
}
}
}

77
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:
DINING PHILOSOPHER PROBLEM
Enter the total no. of philosophers: 5
How many are hungry : 3
Enter philosopher 1 position: 2
Enter philosopher 2 position: 4
Enter philosopher 3 position: 5
1.One can eat at a time 2.Two can eat at a time 3.Exit
Enter your choice: 1
Allow one philosopher to eat at any time
P 3 is granted to eat
P 3 is waiting
P 5 is waiting
P 0 is waiting
P 5 is granted to eat
P 5 is waiting
P 0 is waiting
P 0 is granted to eat
P 0 is waiting
1.One can eat at a time 2.Two can eat at a time 3.Exit
Enter your choice: 2
Allow two philosophers to eat at same time
combination 1
P 3 and P 5 are granted to eat
P 0 is waiting
combination 2
P 3 and P 0 are granted to eat
P 5 is waiting
combination 3
P 5 and P 0 are granted to eat
P 3 is waiting
1.One can eat at a time 2.Two can eat at a time 3.Exit
Enter your choice: 3
RESULT:
Thus the program was executed and verified successfully.

78
JPCOE OPERATING SYSTEMS LAB MANUAL

6.B ) Producer – Consumer Problem.

AIM:To write C programs to simulate Producer – Consumer Problem.


DESCRIPTION:
Producer – consumer problem, is a common paradigm for cooperating processes. 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, there must be available a buffer of items that can be filled by the producer and
emptied by the consumer. This buffer will reside in a region of memory that is shared by the
producer and consumer processes. A producer can produce one item while the consumer is
consuming another item. The producer and consumer must be synchronized, so that the consumer
does not try to consume an item that has not yet been produced.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare and initialize the necessary variables.
Step 3: Create a Producer.
Step 4: Producer (Child Process) performs a down operation and writes a message.
Step 5: Producer performs an up operation for the consumer to consume.
Step 6: Consumer (Parent Process) performs a down operation and reads or consumes the data
(message).
Step 7: Consumer then performs an up operation.
Step 8: Stop the program.
PROGRAM :
SOURCE CODE:
#include<stdio.h>
void main()
{
int buffer[10], bufsize, in, out, produce, consume, choice=0;
in = 0;
out = 0;
bufsize = 10;
while (choice !=3)
{
printf(“\n1. Produce \t 2. Consume \t3. Exit”);
printf(“\nEnter your choice: ”);

79
JPCOE OPERATING SYSTEMS LAB MANUAL

scanf(“%d”, &choice);
switch(choice)
{
case 1: if((in+1)%bufsize==out)
printf(“\nBuffer is Full”);
else
{
printf(“\nEnter the value: “);
scanf(“%d”, &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
break;

case 2: if(in == out)


printf(“\nBuffer is Empty”);
else
{
consume = buffer[out];
printf(“\nThe consumed value is %d”, consume);
out = (out+1)%bufsize;
}
break;
}
}
}

OUTPUT:
Produce 2. Consume 3. Exit
Enter your choice: 2
Buffer is Empty
Produce 2. Consume 3. Exit
Enter your choice: 2
Enter the value: 100
Produce 2. Consume 3. Exit
80
JPCOE OPERATING SYSTEMS LAB MANUAL
Enter your choice: 1

81
JPCOE OPERATING SYSTEMS LAB MANUAL

The consumed values is 100


Produce 2. Consume 3. Exit
Enter your choice: 3

RESULT:
Thus the program was executed and verified successfully.

82
JPCOE OPERATING SYSTEMS LAB MANUAL

6.C )Readers – Writers Problem.


AIM:To write C programs to simulate Readers – Writers Problem.
DESCRIPTION:
A database is to be shared among several concurrent processes. Some of these processes
may want only to read the database, whereas others may want to update (that is, to read and write)
the database. We distinguish between these two types of processes by referring to the former as
readers and to the latter as writers. Obviously, if two readers access the shared data simultaneously,
no adverse affects will result. However, if a writer and some other thread (either a reader or a
writer) access the database simultaneously, chaos may ensue. To ensure that these difficulties do not
arise, we require that the writers have exclusive access to the shared database. This synchronization
problem is referred to as the readers – writer’s problem.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare and initialize the necessary variables.
Step 3: Create a Reader.
Step 4: Reader performs a down operation and read a message in the database.
Step 5: Reader performs an up operation for the Writer to access a message from the database.
Step 6: Write performs a down operation and writes or access the data (message) from the database.
Step 7: Writer then performs an up operation.
Step 8: Stop the program.
PROGRAM:
SOURCE CODE:
//File: mesg.h

#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<stdio.h>
#include<stdlib.h>
#define MKEY1 5543L
#define MKEY2 4354L
#define PERMS 0666
typedef struct
{
long mtype;
char mdata[50];
83
JPCOE OPERATING SYSTEMS LAB MANUAL

}mesg;
//File: sender1.c
#include "mesg.h"
mesg msg;
int main()
{
int mq_id;
int n;
if((mq_id=msgget(MKEY1,PERMS|IPC_CREAT))<0)
{
printf("Sender: Error creating message");
exit(1);
}
msg.mtype=1111L;
n=read(0,msg.mdata,50);
msg.mdata[n]='\0';
msgsnd(mq_id,&msg,50,0);
}
//File: receiver1.c
#include "mesg.h"
mesg msg;
main()
{
int mq_id;
int n;
if( ( mq_id=msgget(MKEY1, PERMS|IPC_CREAT ) ) < 0)
{
printf("receiver: Error opening message");
exit(1);
}
msgrcv(mq_id,&msg,50,1111L,0);
write(1,msg.mdata,50);
msgctl(mq_id,IPC_RMID,NULL);
}

84
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:
$ vi mesg.h
$ vi sender1.c
$ vi receiver1.c
$ cc sender1.c
$ ./a.out
mcet
$ cc receiver1.c
$ ./a.out
mcet

RESULT:
Thus the program was executed and verified successfully.

85
JPCOE OPERATING SYSTEMS LAB MANUAL

7) Write a C program to simulate Bankers Algorithm for Deadlock Avoidance.


AIM:To write a C program to implement bankers algorithm for dead lock avoidance
DESCRIPTION:
In a multiprogramming environment, several processes may compete for a finite number of
resources. 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, because the
resources it has requested are held by other waiting processes. This situation is called a deadlock.
Deadlock avoidance is one of the techniques for handling deadlocks. This approach requires that the
operating system be given in advance additional information concerning which resources a process
will request and use during its lifetime. With this additional knowledge, it can decide for each
request whether or not the process should wait. To decide whether the current request can be
satisfied or must be delayed, the system must consider the resources currently available, the
resources currently allocated to each process, and the future requests and releases of each process.
Banker’s algorithm is a deadlock avoidance algorithm that is applicable to a system with multiple
instances of each resource type.
ALGORITHM:
Step 1: Start the Program.
Step 2: Obtain the required data through char and int datatypes.
Step 3: Enter the filename, index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks.
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution.
PROGRAM:
SOURCE CODE:
/* Bankers algorithm for Deadlock Avoidance */
#include<stdio.h>
struct process
{
int allocation[3];
int max[3];
int need[3];
int finish;
}p[10];

86
JPCOE OPERATING SYSTEMS LAB MANUAL

int main()

87
JPCOE OPERATING SYSTEMS LAB MANUAL

{
int n,i,I,j,avail[3],work[3],flag,count=0,sequence[10],k=0;
printf("\nEnter the number of process:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the %dth process allocated resources:",i);
scanf("%d%d%d",&p[i].allocation[0],&p[i].allocation[1],&p[i].allocation[2]);
printf("\nEnter the %dth process maximum resources:",i);
scanf("%d%d%d",&p[i].max[0],&p[i].max[1],&p[i].max[2]);
p[i].finish=0;
p[i].need[0]=p[i].max[0]-p[i].allocation[0];
p[i].need[1]=p[i].max[1]-p[i].allocation[1];
p[i].need[2]=p[i].max[2]-p[i].allocation[2];
}
printf("\nEnter the available vector:");
scanf("%d%d%d",&avail[0],&avail[1],&avail[2]);
for(i=0;i<3;i++)
work[i]=avail[i];
while(count!=n)
{
count=0;
for(i=0;i<n;i++)
{
flag=1;
if(p[i].finish==0)
if(p[i].need[0]<=work[0])
if(p[i].need[1]<=work[1])
if(p[i].need[2]<=work[2])
{
for(j=0;j<3;j++)
work[j]+=p[i].allocation[j];
p[i].finish=1;
sequence[k++]=i;
flag=0;

88
JPCOE OPERATING SYSTEMS LAB MANUAL

}
if(flag==1)
count++;
}
}
count=0;
for(i=0;i<n;i++)
if(p[i].finish==1)
count++;
printf("\n The safe sequence is:\t");
if(count++==n)
for(i=0;i<k;i++)
printf("%d\n",sequence[i]);
else
printf("SYSTEM IS NOT IN A SAFE STATE \n\n");
return 0;
}

89
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT
$ vi bankersavoidance.c
$ cc bankersavoidance.c
$ ./a.out
Enter the number of process: 3
Enter the 0th process allocated resources: 1 2 3
Enter the 0th process maximum resources: 4 5 6
Enter the 1th process allocated resources: 3 4 5
Enter the 1th process maximum resources: 6 7 8
Enter the 2th process allocated resources: 1 2 3
Enter the 2th process maximum resources: 3 4 5
Enter the available vector: 10 12 11
The safe sequence is: 0 1 2

RESULT:
Thus the program was executed and verified successfully.

90
JPCOE OPERATING SYSTEMS LAB MANUAL

8. Write a C program to simulate Bankers Algorithm for Deadlock Detection(Additional).


AIM:To write a C program to implement Deadlock Detection algorithm

DESCRIPTION:
Deadlock Detection is an important task of OS. As the OS doesn’t take many precautionary
means to avoid it. The OS periodically checks if there is any existing deadlock in the system and
take measures to remove the deadlocks.
Detection
There are 2 different cases in case of Deadlock detection –
 If resource has single Instance
o We make a Wait
 If resources have multiple instances
o We make a different algorithm.
Deadlock Recovery
Deadlock can be recovered by
1) Kill the Process – One way is to kill all the process in deadlock or the second way kill the
process one by one, and check after each if still deadlock exists and do the same till the
deadlock is removed.
2) Pre – emption – The resources that are allocated to the processes involved in deadlock are
taken away (pre – empted) and are transferred to other processes. In this way, system may
recover from deadlock as we may change system state.
3) Rollback – The OS maintains a database of all different states of system, a state when the
system is not in deadlock is called safe state. A rollback to previous ‘n’ number of safe
states in iterations can help in the recover.

ALGORITHM:
Step 1: Start the Program.
Step 2: Obtain the required data through char and in data types.
Step 3: Enter the filename, index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks.
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution.

91
JPCOE OPERATING SYSTEMS LAB MANUAL

PROGRAM:

SOURCE CODE:

/* Bankers algorithm for Deadlock detection */


#include<stdio.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;
printf("enter total no of processes: \n");
scanf("%d",&tp);
printf("enter clain matrix: \n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&c[i][j]);
}
}
printf("enter allocation matrix: \n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&p[i][j]);
}
}
printf("enter resource vector: \n");
for(i=0;i<5;i++)
{
scanf("%d",&r[i]);
}
printf("enter availability vector: \n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);

92
JPCOE OPERATING SYSTEMS LAB MANUAL

temp[i]=a[i];
}
for(i=0;i<4;i++)
{
sum=0;
for(j=0;j<5;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=0;i<4;i++)
{
for(l=1;l<k;l++)
{
if(i!=m[l])
{
flag=1;
for(j=0;j<5;j++)
{
if(c[i][j]>temp[j])
{
flag=0;
break;
}
}
}
}
if(flag==1)
{
m[k]=i;

93
JPCOE OPERATING SYSTEMS LAB MANUAL

k++;
for(j=0;j<5;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are: \n");
for(j=0;j<tp;j++)
{
found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0)
printf("%d\t",j);
}
}

94
JPCOE OPERATING SYSTEMS LAB MANUAL

OUTPUT:
$ vi bankersdetection.c
$ cc bankersdetection.c
$ ./a.out
enter total no of processes:
4
enter clain matrix:
0 1 0 0 1
0 0 1 0 1
0 0 0 0 1
1 0 1 0 1
ent er a llocation matrix:
1 0 1 1 0
1 1 0 0 0
0 0 0 1 0
0 0 0 0 0
ent er r esou rce v ecto r:
2 1 1 2 1
enter availability vector:
0 0 0 0 1
deadlock causing processes are:
0 1

RESULT:
Thus the program was executed and verified successfully.

95
JPCOE OPERATING SYSTEMS LAB MANUAL

9.AIM :Write C programs to demonstrate various thread related concepts.


Threads:
A thread is a path which is followed during a program’s execution. Majority of programs
written now a days run as a single thread. Lets say, for example a program is not capable of reading
keystrokes while making drawings. These tasks cannot be executed by the program at the same time.
This problem can be solved through multitasking so that two or more tasks can be executed
simultaneously.
Multitasking is of two types: Processor based and thread based. Processor based multitasking
is totally managed by the OS, however multitasking through multithreading can be controlled by the
programmer to some extent.

The concept of multi-threading needs proper understanding of these two terms – a process
and a thread. A process is a program being executed. A process can be further divided into
independent units known as threads.
A thread is like a small light-weight process within a process. Or we can say a collection of
threads is what is known as a process.

Applications –
Threading is used widely in almost every field.
 Most widely it is seen over the internet now days where we are using transaction processing
of every type like recharges, online transfer, banking etc.
 Threading is a segment which divide the code into small parts that are of very light weight
and has less burden on CPU memory so that it can be easily worked out and can achieve goal
in desired field.
 The concept of threading is designed due to the problem of fast and regular changes in
technology and less the work in different areas due to less application

96
JPCOE OPERATING SYSTEMS LAB MANUAL

PROGRAM :

SOURCE CODE:
/* Implementing a program using thread */
#include<pthread.h>
#include<stdio.h>
#define NUM_THREADS 3
int je,jo,evensum=0,sumn=0,oddsum=0,evenarr[50],oddarr[50];
void *Even(void *threadid)
{
int i,n;
je=0;
n=(int)threadid;
for(i=1;i<=n;i++)
{
if(i%2==0)
{
evenarr[je]=i;
evensum=evensum+i;
je++;
}
}
}
void *Odd(void *threadid)
{
int i,n;
jo=0;
n=(int)threadid;
for(i=0;i<=n;i++)
{
if(i%2!=0)
{
oddarr[jo]=i;
oddsum=oddsum+i;
jo++;
}
97
JPCOE OPERATING SYSTEMS LAB MANUAL

}
}
void *SumN(void *threadid)
{
int i,n;
n=(int)threadid;
for(i=1;i<=n;i++)
{
sumn=sumn+i;
}
}
int main()
{
pthread_t threads[NUM_THREADS];
int i,t;
printf("Enter a number\n");
scanf("%d",&t);
pthread_create(&threads[0],NULL,Even,(void *)t);
pthread_create(&threads[1],NULL,Odd,(void *)t);
pthread_create(&threads[2],NULL,SumN,(void *)t);
for(i=0;i<NUM_THREADS;i++)
{
pthread_join(threads[i],NULL);
}
printf("The sum of first N natural nos is %d\n",sumn);
printf("The sum of first N even natural nos is %d\n",evensum);
printf("The sum of first N odd natural nos is %d\n",oddsum);
printf("The first N even natural nos is --- \n");
for(i=0;i<je;i++)
printf("%d\n",evenarr[i]);
printf("The first N odd natural nos is --- \n");
for(i=0;i<jo;i++)
printf("%d\n",oddarr[i]);
pthread_exit(NULL);
}

98
OUTPUT:
$ vi threadf.c
$ cc threadf.c -pthread
$ ./a.out
Ente
ra
num
ber
12
The sum of first N natural nos is 78
The sum of first N even natural
nos is 42 The sum of first N
odd natural nos is 36 The first
N even natural nos is----
2
4
6
8
10
12
The first N odd
natural nos is---- 1
3
5
7
9
11

RESULT:
Thus the program was executed and verified successfully.
EX.NO: 10 IMPLEMENT PAGING TECHNIQUE OF MEMORY MANAGEMENT
Paging is a memory management scheme which permits the physical address space of a
process to be non contiguous.In this scheme physical memory is broken into fixed sized
blocks called FRAMES. The logical memory is broken into blocks of same size called
PAGES.When a process is to be executed; its pages are loaded into any available memory
frames from the backing store.
Every address generated by the CPU is divided into two parts
page number( p )
page offset (d )
AIM:
A program to simulate Paging technique of memory management.
ALGORITHM:
Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks.
Step 3: Frames – Physical memory is broken into fixed – sized blocks.
Step 4: Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
Step 5: Display the physical address.
Step 6: Stop the process.
PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int np,ps,i;
int *sa;
clrscr();
printf("Enter how many pages\n");
scanf("%d",&np);
printf("Enter the page size \n");
scanf("%d",&ps);
for(i=0;i<np;i++)
{
sa[i]=(int)malloc(ps);
printf("Page%d\t Address %u\n",i+1,sa[i]);
}
getch();
}

OUTPUT:
Enter how many pages: 5
Enter the page size: 4
Output:
Page1 Address: 1894
Page2 Address: 1902
Page3 Address: 1910
Page4 Address: 1918
Page5 Address: 1926

RESULT:
Thus the program to simulate Paging technique of memory management was written and the
output was verified successfully
EX.NO: 11 IMPLEMENTATION OF MEMORY ALLOCATION METHODS FOR FIXED PARTITION
a) First Fit b) Worst Fit c) Best Fit

a. First Fit Allocation


Aim
To allocate memory requirements for processes using first fit allocation.
Algorithm
1. Declare structures hole and process to hold information about set of holes and
processes respectively.
2. Get number of holes, say nh.
3. Get the size of each hole
4. Get number of processes, say np.
5. Get the memory requirements for each process.
6. Allocate processes to holes, by examining each hole as follows:
a. If hole size > process size then
i. Mark process as allocated to that hole.
ii. Decrement hole size by process size.
b. Otherwise check the next from the set of hole
7. Print the list of process and their allocated holes or unallocated status.
8. Print the list of holes, their actual and current availability.
9. Stop
Program

/* First fit allocation - ffit.c */

#include <stdio.h>

structprocess
{
int size; int flag; int
holeid;
} p[10];
struct hole
{
int size; int actual;
} h[10];

main()
{
int i, np, nh,j;

printf("Enter the number of Holes : "); scanf("%d", &nh);


for(i=0; i<nh; i++)
{
printf("Enter size for hole H%d : ",i); scanf("%d",
&h[i].size);
h[i].actual = h[i].size;
}

printf("\nEnter number of process : " ); scanf("%d",&np);


for(i=0;i<np;i++)
{
printf("enter the size of process P%d : ",i); scanf("%d",
&p[i].size);
p[i].flag = 0;
}
for(i=0; i<np; i++)
{
for(j=0; j<nh; j++)
{
if(p[i].flag != 1)
{
if(p[i].size <=h[j].size)
{
p[i].flag = 1; p[i].holeid = j; h[j].size -
=p[i].size;
}
}
}
}

printf("\n\tFirst Fit\n");
printf("\nProcess\tPSize\tHole"); for(i=0; i<np; i++)
{
if(p[i].flag != 1)
printf("\nP%d\t%d\tNotallocated",i,p[i].size); else
printf("\nP%d\t%d\tH%d", i, p[i].size,p[i].holeid);
}

printf("\n\nHole\tActual\tAvailable"); for(i=0; i<nh ;i++)


printf("\nH%d\t%d\t%d",i,h[i].actual,h[i].size); printf("\n");
}
Output

$ gcc ffit.c

$ ./a.out
Enter the number of Holes :5 Enter size for hole
H0 : 100 Enter size for hole H1 : 500 Enter size
for hole H2 : 200 Enter size for hole H3 : 300
Enter size for hole H4 :600

Enter number of process : 4


enter the size of process P0 : 212 enter the size of process
P1 : 417 enter the size of process P2 : 112 enter the size
of process P3 : 426

First Fit

Process PSize Hole


P0 212 H1
P1 417 H4
P2 112 H1
P3 426 Not allocated

Hole Actual Available


H0 100 100
H1 500 176
H2 200 200
H3 300 300
H4 600 183

Result
Thus processes were allocated memory using first fit method.
11.b BEST FIT ALLOCATION
AIM
To allocate memory requirements for processes using best fit allocation.
ALGORITHM
1. Declare structures hole and process to hold information about set of holes and processes
respectively.
2. Get number of holes, say nh.
3. Get the size of each hole
4. Get number of processes, say np.
5. Get the memory requirements for each process.
6. Allocate processes to holes, by examining each hole as follows:
1. Sort the holes according to their sizes in ascending order
2. If hole size > process size then
1. Mark process as allocated to that hole.
2. Decrement hole size by process size.
3. Otherwise check the next from the set of sorted hole
7. Print the list of process and their allocated holes or unallocated status.
8. Print the list of holes, their actual and current availability.
9. Stop
Program
/* Best fit allocation - bfit.c */
#include <stdio.h>
struct process
{
int size;
int flag;
int holeid;
} p[10]; struct hole
{
int hid; int size; int actual;
} h[10];
main()
{
int i, np, nh, j;
void bsort(struct hole[], int);
printf("Enter the number of Holes : ");
scanf("%d", &nh);
for(i=0; i<nh; i++)
{
printf("Enter size for hole H%d : ",i); scanf("%d", &h[i].size);
h[i].actual = h[i].size;
h[i].hid = i;
}
printf("\nEnter number of process : " );
scanf("%d",&np);
for(i=0;i<np;i++)
{
printf("enter the size of process P%d : ",i);
scanf("%d", &p[i].size); p[i].flag = 0;
}
for(i=0; i<np; i++)
{
bsort(h, nh);
for(j=0; j<nh; j++)
{
if(p[i].flag != 1)
{
if(p[i].size <= h[j].size)
{
p[i].flag = 1;
p[i].holeid = h[j].hid;
h[j].size -= p[i].size;
}}}}
printf("\n\tBest Fit\n");
printf("\nProcess\tPSize\tHole");
for(i=0; i<np; i++)
{
if(p[i].flag != 1)
printf("\nP%d\t%d\tNot allocated", i, p[i].size); else
printf("\nP%d\t%d\tH%d", i, p[i].size, p[i].holeid);
}
printf("\n\nHole\tActual\tAvailable"); for(i=0; i<nh ;i++)
printf("\nH%d\t%d\t%d", h[i].hid, [i].actual, h[i].size);
printf("\n");
}
void bsort(struct hole bh[], int n)
{
struct hole temp;
int i,j;
for(i=0; i<n-1; i++)
{
for(j=i+1; j<n; j++)
{
if(bh[i].size > bh[j].size)
{
temp = bh[i];
bh[i] = bh[j];
bh[j] = temp;
}
}
}
}

Output
$ gcc bfit.c
$ ./a.out
Enter the number of Holes : 5
Enter size for hole H0 : 100
Enter size for hole H1 : 500
Enter size for hole H2 : 200
Enter size for hole H3 : 300
Enter size for hole H4 : 600
Enter number of process : 4
enter the size of process P0 : 212
enter the size of process P1 : 417
enter the size of process P2 : 112
enter the size of process P3 : 426
Best Fit
Process PSize Hole
P0 212 H3
P1 417 H1
P2 112 H2
P3 426 H4
Hole Actual Available
H1 500 83
H3 300 88
H2 200 88
H0 100 100
H4 600 174

RESULT
Thus processes were allocated memory using best fit method.
12.Write C programs to simulate Page Replacement Algorithms: FIFO, LRU.
Page Replacement Algorithms:
Page replacement is basic to demand paging. It completes the separation between logical
memory and physical memory. With this mechanism, an enormous virtual memory can be provided
for programmers on a smaller physical memory. There are many different page-replacement
algorithms. Every operating system probably has its own replacement scheme. 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. If the recent past is used as an approximation of
the near future, then the page that has not been used for the longest period of time can be replaced.
This approach is the Least Recently Used (LRU) algorithm. LRU replacement associates with each
page the time of that page's last use. When a page must be replaced, LRU chooses the page that has
not been used for the longest period of time. 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.
12.a)FIFO.
AIM:To Simulate FIFO page replacement algorithms.

ALGORITHM:
Step 1: Start the program
Step 2: Read the number of frames
Step 3: Read the number of pages
Step 4: Read the page numbers
Step 5: Initialize the values in frames to -1
Step 6: Allocate the pages in to frames in First in first out order.
Step 7: Display the number of page faults.
Step 8: Stop the program
PROGRAM:
SOURCE CODE:

/* A program to simulate FIFO Page Replacement Algorithm */


#include<stdio.h>
main()
{
int a[5],b[20],n,p=0,q=0,m=0,h,k,i,q1=1;
char f='F';
printf("Enter the Number of Pages:");
scanf("%d",&n);
printf("Enter %d Page Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
{
if(p==0)
{
if(q>=3)
q=0;
a[q]=b[i];
q++;
if(q1<3)
{
q1=q;
}
}
printf("\n%d",b[i]);
printf("\t");
for(h=0;h<q1;h++)
printf("%d",a[h]);
if((p==0)&&(q<=3))
{
printf("-->%c",f);
m++;
}
p=0;

for(k=0;k<q1;k++)
{
if(b[i+1]==a[k])
p=1;
}
}
printf("\nNo of faults:%d",m);
}

OUTPUT:

$ vi fifo.c
$ cc fifo.c
$ ./a.out

Enter the Number of Pages: 12


Enter 12 Page Numbers:
2 3 2 1 5 2 4 5 3 2 5 2

2 2-->F
3 23-->F
2 23
1 231-->F
5 531-->F
2 521-->F
4 524-->F
5 524
3 324-->F
2 324
5 354-->F
2 352-->F

No of faults: 9

RESULT:
Thus the program was executed and verified successfully.
12.b LRU
AIM:To Simulate LRU page replacement algorithms.

ALGORITHM:
Step 1: Start the program.
Step 2: Read the number of frames.
Step 3: Read the number of pages.
Step 4: Read the page numbers.
Step 5: Initialize the values in frames to -1.
Step 6: Allocate the pages in to frames by selecting the page that has not been used for the longest
period of time.
Step 7: Display the number of page faults.
Step 8: Stop the program.
PROGRAM :
SOURCE CODE:
/* A program to simulate LRU Page Replacement Algorithm */
#include<stdio.h>
main()
{
int a[5],b[20],p=0,q=0,m=0,h,k,i,q1=1,j,u,n;
char f='F';
printf("Enter the number of pages:");
scanf("%d",&n);
printf("Enter %d Page Numbers:",n);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
{
if(p==0)
{
if(q>=3)
q=0;
a[q]=b[i];
q++;
if(q1<3)
{
q1=q;
}
}
printf("\n%d",b[i]);
printf("\t");
for(h=0;h<q1;h++)
printf("%d",a[h]);
if((p==0)&&(q<=3))
{
printf("-->%c",f);
m++;
}
p=0;

if(q1==3)
{
for(k=0;k<q1;k++)
{
if(b[i+1]==a[k])
p=1;
}
for(j=0;j<q1;j++)
{
u=0;
k=i;
while(k>=(i-1)&&(k>=0))
{
if(b[k]==a[j])
u++;
k--;
}
if(u==0)
q=j;
}
}
else
{
for(k=0;k<q;k++)
{
if(b[i+1]==a[k])
p=1;
}
}
}
printf("\nNo of faults:%d",m);
}

OUTPUT:
$ vi lru.c
$ cc lru.c
$ ./a.out
Enter the number of pages: 12
Enter 12 Page Numbers:
2 3 2 1 5 2 4 5 3 2 5 2
2 2-->F
3 23-->F
2 23
1 231-->F
5 251-->F
2 251
4 254-->F
5 254
3 354-->F
2 352-->F
5 352
2 352
No of faults: 7
RESULT:
Thus the program was executed and verified successfully.
EX.NO 13 . IMPLEMENTATION OF THE VARIOUS FILE ORGANIZATION TECHNIQUES
AIM:
Write a C program to simulate the following file organization techniques
a) Single level directory b) Two level directory c) Hierarchical
DESCRIPTION
The directory structure is the organization of files into a hierarchy of folders. In
a single-level directory system, all the files are placed in one directory. There is a root
directory which has all files. It has a simple there are no sub directories. Advantage of
single level directory system is that it is easy to find a file in the directory.
In the two-level directory system, each user has own user file directory (UFD).
The system maintains a master block that has one entry for each user. This master
block contains the addresses of the directory of the users. When a user job starts or a
user logs in, the system's master file directory (MFD) is searched. When a user refers
to a particular file, only his own UFD is searched. This effectively solves the name
collision problem and isolates users from one another. Hierarchical directory structure
allows users to create their own subdirectories and to organize their files accordingly.
A tree is the most common directory structure. The tree has a root directory, and every
file in the system has a unique path name. A directory (or subdirectory) contains a set
of files or subdirectories.
PROGRAM
// 13. A SINGLE LEVEL DIRECTORY ORGANIZATION
#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir;
void main()
{
int i,ch;
char f[30];
clrscr();
dir.fcnt = 0;
printf("\nEnter name of directory -- ");
scanf("%s", dir.dname);
while(1)
{
printf("\n\n 1. Create File\t2. Delete File\t3. Search File \n 4. Display Files\t5.
Exit\nEnter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n Enter the name of the file -- ");
scanf("%s",dir.fname[dir.fcnt]);
dir.fcnt++;
break;
case 2: printf("\n Enter the name of the file -- ");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is deleted ",f);
strcpy(dir.fname[i],dir.fname[dir.fcnt-1]);
break;
}
}
if(i==dir.fcnt)
printf("File %s not found",f);
else
dir.fcnt--;
break;
case 3: printf("\n Enter the name of the file -- ");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is found ", f);
break;
}
}
if(i==dir.fcnt)
printf("File %s not found",f);
break;
case 4: if(dir.fcnt==0)
printf("\n Directory Empty");
else
{
printf("\n The Files are -- ");
for(i=0;i<dir.fcnt;i++)
printf("\t%s",dir.fname[i]);
}
break;
default: exit(0);
}}
getch();
}
OUTPUT:
Enter name of directory -- CSE
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 1
Enter the name of the file -- A
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 1
Enter the name of the file -- B
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 1
Enter the name of the file -- C
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 4
The Files are -- A B C
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 3
Enter the name of the file – ABC
File ABC not found
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 2
Enter the name of the file – B
File B is deleted
1. Create File 2. Delete File 3. Search File
4. Display Files 5. Exit Enter your choice – 5
//13.b TWO LEVEL DIRECTORY ORGANIZATION
#include<stdio.h>
struct
{
char dname[10],fname[10][10];
int fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k;
char f[30], d[30];
clrscr();
dcnt=0;
while(1)
{
printf("\n\n 1. Create Directory\t 2. Create File\t 3. Delete File");
printf("\n 4. Search File \t \t 5. Display \t 6. Exit \t Enter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n Enter name of directory -- ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2: printf("\n Enter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",dir[i].fname[dir[i].fcnt]);
dir[i].fcnt++;
printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d);
break;
case 3: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is deleted ",f);
dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
printf("File %s not found",f);
goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
case 4: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{

if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is found ",f);
goto jmp1;
}
}
printf("File %s not found",f);
goto jmp1;
}
}
printf("Directory %s not found",d);
jmp1: break;
case 5: if(dcnt==0)
printf("\nNo Directory's ");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}
break;
default:exit(0);
}
}
getch();
}

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

Enter name of directory -- DIR2


Directory created

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


4. Search File 5. Display 6. Exit Enter your choice -- 2
Enter name of the directory – DIR1
Enter name of the file -- A1
File created
1. Create Directory 2. Create File 3. Delete File
4. Search File 5. Display 6. Exit Enter your choice -- 2
Enter name of the directory – DIR1
Enter name of the file -- A2
File created
1. Create Directory 2. Create File 3. Delete File
4. Search File 5. Display 6. Exit Enter your choice -- 2
Enter name of the directory – DIR2
Enter name of the file -- B1
File created
1. Create Directory 2. Create File 3. Delete File
4. Search File 5. Display 6. Exit Enter your choice -- 5
Directory Files
DIR1 A1 A2
DIR2 B1

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


4. Search File 5. Display 6. Exit Enter your choice -- 4
Enter name of the directory – DIR
Directory not found
1. Create Directory 2. Create File 3. Delete File
4. Search File 5. Display 6. Exit Enter your choice -- 3
Enter name of the directory – DIR1
Enter name of the file -- A2
File A2 is deleted
1. Create Directory 2. Create File 3. Delete File
4. Search File 5. Display 6. Exit Enter your choice – 6
//13.c HIERARCHICAL DIRECTORY ORGANIZATION

#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 lx,int 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 forfile :");
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 sub directories/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]); }}}
OUTPUT:
Enter Name of dir/file (under root): ROOT
Enter 1 for Dir / 2 For File : 1
No of subdirectories / files (for ROOT) :2
Enter Name of dir/file (under ROOT):USER 1
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for USER 1):1
Enter Name of dir/file (under USER 1):SUBDIR
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for SUBDIR):2
Enter Name of dir/file (under USER 1):
JAVA Enter 1 for Dir /2 for file:1
No of subdirectories /files (for JAVA): 0
Enter Name of dir/file (under SUBDIR):VB
Enter 1 for Dir /2 for file:1
No of subdirectories /files (for VB): 0

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


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

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

Thus the C program to simulate the file organization techniqueswas written and output was
verified successfully.
Ex.No 14 Implementation of File Allocation Strategies

14.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>
void 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;
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();
}
EX.NO:14b INDEXED FILE ALLOCATION
AIM:
To implement Indexed file allocation technique in C.
ALGORITHM:
1. Start
2. Declare the index block no. and total no.of files in a block
3. Get the index block no. and total no.of 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>
void 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;
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( );
}
EX NO: 14.C. LINKED FILE ALLOCATION
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>
int f[50],i,k,j,inde[50],n,c,count=0,p;
void main()
{
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++)
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();}

15. Write C programs to simulate implementation of Disk Scheduling Algorithms: FCFS, SSTF.
A] Aim : Write C programs to simulate implementation FCFS Disk Scheduling Algorithm
The simplest form of disk scheduling is, of course, the first-come, first-served (FCFS)
algorithm. This algorithm is intrinsically fair, but it generally does not provide the fastest service.
Consider, for example, a disk queue with requests for I/O to blocks on cylinders 98, 183, 37, 122,
14, 124, 65, 67. If the disk head is initially at cylinder 53, it will first move from 53 to 98, then to
183, 37, 122, 14, 124, 65, and finally to 67, for a total head movement of 640 cylinders.
Algorithm:
1. Let Request array represents an array storing indexes of tracks that have been requested in
ascending order of their time of arrival. ‘head’ is the position of disk head.
2. Let us one by one take the tracks in default order and calculate the absolute distance of the
track from the head.
3. Increment the total seek count with this distance.
4. Currently serviced track position now becomes the new head position.
5. Go to step 2 until all tracks in request array have not been serviced.

#include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
for(i=1;i<=n;i++)
scanf("%d",&queue[i]);
printf("Enter the initial head position\n");
scanf("%d",&head);
queue[0]=head;
for(j=0;j<=n-1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with
seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}
OUTPUT
Enter the max range of disk
200
Enter the size of queue request
8
Enter the queue of disk positions to be read
90 120 35 122 38 128 65 68
Enter the initial head position
50
Disk head moves from 50 to 90 with seek
40
Disk head moves from 90 to 120 with seek
30
Disk head moves from 120 to 35 with seek
85
Disk head moves from 35 to 122 with seek
87
Disk head moves from 122 to 38 with seek
84
Disk head moves from 38 to 128 with seek
90
Disk head moves from 128 to 65 with seek
63
Disk head moves from 65 to 68 with seek
3
Total seek time is 482
Average seek time is 60.250000

RESULT:
Thus the program was executed and verified successfully.
B] Aim : Write C programs to simulate implementation SSTF Disk Scheduling Algorithm

SSTF stands for Shortest Time First which very uses full of learning about how the disk drive
manages the data having the shortest seek time.
Algorithm :
1. Let Request array represents an array storing indexes of tracks that have been requested.
‘head’ is the position of disk head.
2. Find the positive distance of all tracks in the request array from head.
3. Find a track from requested array which has not been accessed/serviced yet and has
minimum distance from head.
4. Increment the total seek count with this distance.
5. Currently serviced track position now becomes the new head position.
6. Go to step 2 until all tracks in request array have not been serviced.

#include<stdio.h>
#include<conio.h>
#include<math.h>
int main()
{
int queue[100],t[100],head,seek=0,n,i,j,temp;
float avg;
// clrscr();
printf("*** SSTF Disk Scheduling Algorithm ***\n");
printf("Enter the size of Queue\t");
scanf("%d",&n);
printf("Enter the Queue\t");
for(i=0;i<n;i++)
{
scanf("%d",&queue[i]);
}
printf("Enter the initial head position\t");
scanf("%d",&head);
for(i=1;i<n;i++)
t[i]=abs(head-queue[i]);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(t[i]>t[j])
{
temp=t[i];
t[i]=t[j];
t[j]=temp;
temp=queue[i];
queue[i]=queue[j];
queue[j]=temp;
}
}
}
for(i=1;i<n-1;i++)
{
seek=seek+abs(head-queue[i]);
head=queue[i];
}
printf("\nTotal Seek Time is%d\t",seek);
avg=seek/(float)n;
printf("\nAverage Seek Time is %f\t",avg);
return 0;
}

OUTPUT:

*** SSTF Disk Scheduling Algorithm ***


Enter the size of Queue 5
Enter the Queue 10 17 2 15 4
Enter the initial head position 3
Total Seek Time is14
Average Seek Time is 2.800000

RESULT:
Thus the program was executed and verified successfully.
ADDITIONAL PROGRAMS
11. SHELL PROGRAMMING
7. Shell or the Command interpreter is the mediator which interprets the commands and then
conveys them to the kernel which ultimately executes them.
8. Kernel is usually stored in a file called ‘UNIX’ where as the shell program in a file called
‘sh’.
9. Types of shells:-.
i. Bourne shell (sh) or Bourne again shell (bash)
ii. C shell (csh)
iii. Korn shell (ksh)
10. A shell program is nothing but a series of unix commands.
11. Instead of specifying one job at a time, the shell is given a to-do-list – a program – that
carries out an entire procedure.
12. Such programs are known as shell scripts.
Shell programming language incorporates most of the features that most modern day
programming languages offer.
Shell variables –
Rules for building shell variables are as follows:
6) A variable name is any combination of alphabets, digits and an underscore (‘_’).
7) No commas or blanks are allowed within a variable name.
8) The first character of a variable name must either be an alphabet or an underscore.
9) Variable names should be of any reasonable length.
10) Variable names are case sensitive.
Keywords for accepting input – read
Displaying output - echo
Assigning value to variables –
Values can be assigned to variables through read statement or also by using a simple
assignment operator. For ex: age=30
Note : While assigning values to variables using assignment operator, no spaces to be given on
either side of it. If the variable doesn’t exist it will be created and value assigned
7. Unix-defined variables or System variables or Environment variables
8. User- defined variables
Note : To print or access value of a variable use ‘$’ .
For ex: To print value of variable ‘flag‘ write - echo $flag
Arithmetic in Shell script -
6. All shell variables are string variables, hence to carry out arithmetic operations use expr
command which evaluates arithmetic expressions.
7. More than one assignment can be done in a single statement.
8. Before and at the end of expr keyword use ` (back quote) sign not the (single quote i.e. ')
sign which is generally above TAB key.
9. Terms of the expression provided to expr must be separated by blanks. Thus expression
expr 10+20 is invalid.
10. The ‘*” symbol must be preceded by a \ ,otherwise the shell treats it as a
wildcard character for all files in the current directory
OPERATORS USED IN SHELL SCRIPT –
OPERATOR MEANING
–gt Greater than
–lt Less than
–ge Greater than or equal to
–le Less than or equal to
–ne Not equal to
–eq Equal to
–a Logical AND
–o Logical OR
! Logical NOT
CONTROL INSTRUCTIONS IN SHELLS -
There are four types of control instructions in shell :
• Sequence Control Instruction.
• Selection or Decision control Instruction
• Repetition or Loop control Instruction
• Case Control Instruction
Decision statements –
If-then-else-fi statements:
if condition then Commands else Commands fi
4) For statements :
for control variable in value1 value 2 value3 do
Command list done
5) While statements : while control command do
Command list Done
6) Until statements:
until control command do
Command list done
Case statements:-
case value in
choice 1) commands;
choice 2) commands;
esac.

Steps to write and execute a script


1. Open the terminal. Go to the directory where you want to create your script.
2. Create a file with . sh extension.
3. Write the script in the file using an editor.
4. Make the script executable with command chmod +x <fileName>.
5. Run the script using ./<fileName>.
• Concatenate two strings.

AIM:To write a shell program to concatenate two strings.


ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.

Step 3: Read the first string.

Step 4: Read the second string.


Step 5: Concatenate the two strings.
Step 6: Enter into the escape mode for the execution of the result and verify the output.
Step 7: Stop the program.
SOURCE CODE
echo “enter the first string”
read str1
echo “enter the second string”
read str2
echo “the concatenated string is” $str1$str2

OUTPUT:
$ vi concat.sh
$ sh concat.sh
Enter first string: Hello
Enter first string: World
The concatenated string is HelloWorld

RESULT:
Thus the shell program to concatenate two strings is executed and output is verified
successfully.
• Comparison of Two Strings

AIM:To write a shell program to compare the two strings.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.
Step 3: Read the first string.
Step 4: Read the second string.
Step 5: Compare the two strings using the if loop.
Step 6: If the condition satisfies then print that two strings are equal else print two strings are not
equal.
Step 7: Enter into the escape mode for the execution of the result and verify the output.
Step 8: Stop the program.

SOURCE CODE:
echo "enter a string 1"
read first
echo "enter a string 2"
read second
if [ $first = $second ] # this “ =” for other than digits equals
then
echo “strings are equal”
else
echo “strings are unequal”
fi

OUTPUT:
$ vi compare1.sh
$ sh compare1.sh
enter a string 1
abcxyz
enter a string 2
abcxyz
strings are equal
OUTPUT:
$ vi compare1.sh
$ sh compare1.sh
enter a string 1
hai
enter a string 2
cse
strings are unequal

RESULT:
Thus the shell program to compare the two strings is executed and output is verified
successfully.
• Comparison Of Two Strings From Command Lines

AIM:To write a shell program to compare of two strings from command lines.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.
Step 3: Read the first string.
Step 4: Read the second string.
Step 5: Compare the two strings using the if loop.
Step 6: If the condition satisfies then print that two strings are equal else print two strings are not
equal.
Step 7: Enter into the escape mode for the execution of the result and verify the output.
Step 8: Stop the program.

SOURCE CODE:
if [ $1 = $2 ]
then
echo "Strings are equal….."
else
echo "Strings are not equal….."
fi

OUTPUT:
$ vi compare2.sh
$ sh compare2.sh methodist methodist
Strings are equal…..
$ sh compare2.sh methodist tsidohtem
Strings are not equal…..

RESULT:
Thus the shell program to compare the two strings from command lines is executed and
output is verified successfully.
• Generate Fibonacci Series

AIM:To write a shell program to generate fibonacci series.

ALGORITHM:
Step 1: Start the program.
Step 2: Initialise a to 0 and b to 1.
Step 3: Print the values of ‘a’ and ‘b’.
Step 4: Add the values of ‘a'’ and ‘b’. Store the added value in variable 'c'.
Step 5: Print the value of ‘c’.
Step 6: Initialise ‘a’ to ‘b’ and ‘b’ to ‘c’.
Step 7: Repeat the steps 3, 4, 5 till the value of ‘a’ is less than 10.
Step 8: Stop the program.

SOURCE CODE:
echo “enter the no. of numbers in the series”
read n
a=0
b=1
d=2
echo “$a”
echo “$b”
while [ $d -lt $n ]
do
c=`expr $a + $b`
echo “$c”
a=$b
b=$c
d=`expr $d + 1`
done
OUTPUT:
$ vi fibonacci.sh
$ sh fibonacci.sh
enter the no. of numbers in the series
10
0
1
1
2
3
5
8
13
21
34

RESULT:
Thus the shell program to find the fibonacci series is executed and output is verified
successfully.
• Even or Odd Number

AIM:To write a shell program to find even or odd number.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.
Step 3: Read the number.
Step 4: Evaluate whether the given number Even or Odd.
Step 5: Print the Result and verify the output.
Step 6: Stop the program.

SOURCE CODE:
echo “enter the number”
read n
r=1
r=`expr $n % 2`
if [ $r -eq 0 ] # “-eq” for digits or numbers
then
echo “even”
else
echo “odd”
fi

OUTPUT:
$ vi evenodd.sh
$ sh evenodd.sh
enter the number
5
odd

RESULT:
Thus the shell program to find whether the given number is even or odd number is executed
and output is verified successfully.
• List of Even Numbers in a Given Limit

AIM:To write a shell program to list of even numbers in a given limit.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter into the vi editor and go to the insert mode for entering the code.
Step 3: Read the limit.
Step 4: Read the second string.
Step 5: Evaluate all Even in the given limit.
Step 6: Print the Result and verify the output.
Step 7: Stop the program.

SOURCE CODE:
echo -n "enter the limit:"
x=2
read num
while [ $x -lt $num ]
do
echo -n "$x \t"
x=`expr $x + 2`
done

OUTPUT:

$ vi evennums.sh
$ sh evennums.sh
enter the limit:20
2 4 6 8 10 12 14 16 18

RESULT:
Thus the shell program to find list of even numbers in a given limit is executed and output is
verified successfully.
VIVA – VOCE QUESTIONS
• What is an operating system?
• What are short, long and medium-term scheduling?
• Explain the concept of the batched operating systems?
• What is purpose of different operating systems?
• What is virtual memory?
• What is Throughput, Turnaround time, waiting time and Response time?
• What are the various components of a computer system?
• What is a Real-Time System?
• Explain the concept of the Distributed systems?
• What are the different operating systems?
• What is busy waiting?
• What are system calls?
• What are various scheduling queues?
• What are the states of a process?
• What is a job queue?
• What is a ready queue?
• What are turnaround time and response time?
• What are the operating system components?
• Why thread is called as a lightweight process?
• What are operating system services?
• What is a process?
• What are the different job scheduling in operating systems?
• What is dual-mode operation?
• What is a device queue?
• What are the different types of Real-Time Scheduling?
• What is starvation?
• What is a long term scheduler & short term schedulers?
• What is fragmentation?
• What is the state of the processor, when a process is waiting for some event to occur?
• What is the difference between Primary storage and secondary storage?
• What is the difference between Complier and Interpreter?
• What are the different functions of Scheduler
• What are local and global page replacements?
• What are the different operating systems?
• What are the basic functions of an operating system?
• What is kernel?
• What is a process?
• What are the states of a process?
40. What is starvation and aging?
41. What is context switching?
42. What is a thread?
43. What is process synchronization?
44. What is virtual memory?
45. What is fragmentation? Tell about different types of fragmentation?
46. What is logical and physical addresses space?
47. What is Memory-Management Unit (MMU)?
48. What is a Real-Time System?
49. What is process migration?
50. Difference between Primary storage and secondary storage?
51. Define compactions.
52. What are the disadvantages of context switching?
53. What is Dispatcher?
54. What is the Translation Lookaside Buffer (TLB)?

You might also like