0% found this document useful (0 votes)
8 views88 pages

Csit (r22) 2-1 Operating Systems Lab Manual

The document is a laboratory manual for Operating Systems, prepared for B. Tech II Year students at Malla Reddy College of Engineering & Technology. It outlines the vision, mission, program educational objectives, specific outcomes, and general laboratory instructions, along with a detailed index of practical programs and exercises related to Linux commands and operating system concepts. The manual emphasizes the importance of professionalism, technical skills, and ethical values in engineering education.

Uploaded by

bala raman
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)
8 views88 pages

Csit (r22) 2-1 Operating Systems Lab Manual

The document is a laboratory manual for Operating Systems, prepared for B. Tech II Year students at Malla Reddy College of Engineering & Technology. It outlines the vision, mission, program educational objectives, specific outcomes, and general laboratory instructions, along with a detailed index of practical programs and exercises related to Linux commands and operating system concepts. The manual emphasizes the importance of professionalism, technical skills, and ethical values in engineering education.

Uploaded by

bala raman
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/ 88

OPERATING SYSTEMS

LABORATORY MANUAL
(R22A0587)

B. TECH
II YEAR – I SEM
(2024-25)

PREPARED BY
B.ARUNA KUMARI

DEPARTMENT OF COMPUTER SCIENCE & INFORMATION TECHNOLOGY

MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY


(Autonomous Institution – UGC, Govt. of India)
(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, INDIA.
DEPARTMENT OF COMPUTER SCIENCE & INFORMATION TECHNOLOGY

VISION

 To achieve high quality in technical education that provides the skills and
attitude to adapt to the global needs of the Information Technology sector,
through academic and research excellence.

MISSION

 To equip the students with the cognizance for problem solving and
toimprove the teaching pedagogy by using innovative techniques.

 To strengthen the knowledge base of the faculty and students with


motivation towards possession of effective academic skills and relevant
research experience

 To promote the necessary moral and ethical values among the engineers,
forthe betterment of the society
PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

PEO1: PROFESSIONALISM & CITIZENSHIP


To create and sustain a community of learning in which students acquire knowledge
and learn to apply it professionally with due consideration for ethical, ecological and
economic issues.
PEO2: TECHNICAL ACCOMPLISHMENTS
To provide knowledge based services to satisfy the needs of society and the industry
byproviding hands on experience in various technologies in core field.
PEO3: INVENTION, INNOVATION AND CREATIVITY
To make the students to design, experiment, analyze, interpret in the core field
withthe help of other multi disciplinary concepts wherever applicable.
PEO4: PROFESSIONAL DEVELOPMENT
To educate the students to disseminate research findings with good soft skills and
become a successful entrepreneur.
PEO5: HUMAN RESOURCE DEVELOPMENT
To graduate the students in building national capabilities in technology, education and
research.
PROGRAM SPECIFIC OUTCOMES (PSOs)

After the completion of the course, B. Tech Information Technology, the


graduates will havethe following Program Specific Outcomes:

1. Fundamentals and critical knowledge of the Computer System:-


Able to Understand the working principles of the computer System and
its components , Apply the knowledge to build, asses, and analyze the
softwareand hardware aspects of it .

2. The comprehensive and Applicative knowledge of Software


Development: Comprehensive skills of Programming Languages,
Software process models, methodologies, and able to plan, develop, test,
analyze, and manage the software and hardware intensive systems in
heterogeneous platforms individually or working in teams.

3. Applications of Computing Domain & Research: Able to use the


professional, managerial, interdisciplinary skill set, and domain specific
tools in development processes, identify the research gaps, and provide
innovative solutions to them.
PROGRAM OUTCOMES (POs)

Engineering Graduates should possess the following:


1. Engineering knowledge: Apply the knowledge of mathematics, science,
engineering fundamentals, and an engineering specialization to the solution of
complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
3. Design / development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified
needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge
and research methods including design of experiments, analysis and interpretation
of data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding
of the engineering and management principles and apply these to one’s own work,
as a member and leader in a team, to manage projects and in multi disciplinary
environments.
12. Life- long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of
technological change.
MALLA REDDY COLLEGE OF ENGINEERING & TECHNOLOGY
Maisammaguda, Dhulapally Post, Via Hakimpet, Secunderabad – 500100

Department of Computer Science & Information Technology

GENERAL LABORATORY INSTRUCTIONS

1. Students are advised to come to the laboratory at least 5 minutes before (to the starting time),those
who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with the
synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any) neededin the
lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system allottedto you
by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation note book,
and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain the
discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which should be
utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab sessions.
Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody found
loitering outside the lab / class without permission during working hours will be treated seriously and
punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after
completing the task (experiment) in all aspects. He/she must ensure the system / seat is keptproperly.

HEAD OF THE DEPARTMENT PRINCIPAL


INDEX

S.NO LIST OF PROGRAMS PAGE NO.


To Install Ubuntu Linux and practice LINUX Commands 8

WEEK-1 Practice File handling utilities, Process utilities, Disk utilities, Networking 20
commands, Filters, Test processing utilities and Backup utilities.
WEEK-2 Write a shell script that receives any number of file names as arguments 29
checks if every argument supplied is a file or directory and reports
accordingly. Whenever the argument is a file it reports no of lines present
in it.
WEEK-3 Simulate the following CPU scheduling algorithms. 31
a)FCFS b) SJF c) Round Robin d) Priority.
WEEK-4 Simulate Bankers Algorithm for Dead Lock Avoidance; Simulate Bankers 40
Algorithm for Dead Lock Prevention.
a) Write a C program to simulate the concept of Dining-philosophers 48
WEEK-5 problem.
B) Write a C program to simulate producer-consumer problem using 51
Semaphores
a) Write a program that illustrates communication between two 53
WEEK-6 processes using named pipes or FIFO.
b) Write a C program that receives a message from message queue and 57
display them.
WEEK-7 Write a C program that illustrates two processes communicating using 60
Shared memory
WEEK-8 Simulate all page replacement algorithms 62
a) FIFO b) LRU c) OPTIMAL
WEEK-9 Write a C program that takes one or more file/directory names as 73
command line input and reports following information
a) File Type b) Number Of Links c) Time of last Access d) Read, write
and execute permissions
WEEK-10 Write a C program to simulate disk scheduling algorithms. 75
a) FCFS b) SCAN c) C-SCAN
OPERATING SYSTEMS LAB PAGE 1
To Install Ubuntu Linux – Complete Step by Step

OPERATING SYSTEMS LAB PAGE 2


Now again select free space from the table and click add option. Now select size to be around twice the
size ofyour ram that is around 1000 mb if your ram size is 512mb and select use as swap area and clickok.

OPERATING SYSTEMS LAB PAGE 3


Step 6 : Click Install now button and then the wizardwill ask you location. Select your location and

clickforward.

OPERATING SYSTEMS LAB PAGE 4


OPERATING SYSTEMS LAB PAGE 5
OPERATING SYSTEMS LAB PAGE 6
OPERATING SYSTEMS LAB PAGE 7
A-Z Index of the Bash command line for Linux
a

alias Create an alias •

apropos Search Help manual pages (man -k)

apt-get Search for and install software packages (Debian/Ubuntu)

aptitude Search for and install software packages (Debian/Ubuntu)

aspell Spell Checker

awk Find and Replace text, database sort/validate/index

basename Strip directory and suffix

fromfilenamesbash GNU Bourne-

Again SHell

bc Arbitrary precision calculatorlanguage

bg Send to background

bind Set or display readline key and function

bindings•break Exit from a loop •

builtin Run a shell builtin

bzip2 Compress or decompress named file(s)

cal Display a calendar

case Conditionally perform a command

cat Concatenate and print (display) the content

offilescd Change Directory

cfdisk Partition table manipulator for Linux

chattr Change file attributes on a Linux filesystem

OPERATING SYSTEMS LAB PAGE 8


chgrp Change group ownership

chmod Change access

permissions chown Change file

owner andgroup

chroot Run a command with a different

rootdirectorychkconfig System services (runlevel)

cksum Print CRC checksum and

bytecountsclear Clear terminal screen

cmp Compare two files

comm Compare two sorted files line by line

command Run a command - ignoring shell

functionscontinue Resume the next iteration of a

loop

cp Copy one or more files to another

locationcron Daemon to execute scheduled

commands crontab Schedule a command to

run at a later time csplit Split a file into

context-determined pieces curl Transfer

data from or to a server

cut Divide a file into several parts

date Display or change the date & time

dc Desk Calculator

dd Convert and copy a file, write disk headers, boot

recordsddrescue Data recovery tool

declare Declare variables and give them

attributes•df Display free disk space

diff Display the differences between 2 files

OPERATING SYSTEMS LAB PAGE 9


dir Briefly list directorycontents

dircolors Colour setup for `ls'

dirname Convert a full pathname to just a path

dirs Display list of remembered directories

dmesg Print kernel & driver messages

du Estimate file space usage

echo Display message on screen

egrep Search file(s) for lines that match an extendedexpression

eject Eject removable media

enable Enable and disable builtin shell commands

env Environment variables

eval Evaluate severalcommands/arguments

exec Execute a command

exit Exit the shell

expect Automate arbitrary applications accessed over aterminal

expand Convert tabs to spaces

export Set an environment variable

expr Evaluate expressions

false Do nothing, unsuccessfully

fdformat Low-level format a floppydisk

fdisk Partition table manipulator forLinux

fg Send job to foreground

fgrep Search file(s) for lines that match a fixedstring

file Determine file type

find Search for files that meet a desiredcriteria

OPERATING SYSTEMS LAB PAGE 10


fmt Reformat paragraph text

fold Wrap text to fit a specified width.

for Expand words, and execute commands

format Format disks or tapes

free Display memory usage

fsck File system consistency check andrepair

ftp File Transfer Protocol

function Define Function Macros

fuser Identify/kill the process that is accessing a file

gawk Find and Replace text withinfile(s)

getopts Parse positional parameters

grep Search file(s) for lines that match a givenpattern

groupadd Add a user security group

groupdel Delete a group

groupmod Modify a group

groups Print group names a user is in

gzip Compress or decompress named file(s)

hash Remember the full pathname of a nameargument

head Output the first part of file(s)

help Display help for a built-in command

history Command History

hostname Print or set system name

iconv Convert the character set of afile


id Print user and group id's

OPERATING SYSTEMS LAB PAGE 11


if Conditionally perform acommand

ifconfig Configure a network interface

install Copy files and set attributes

ip Routing, devices and tunnels

jobs List active jobs

join Join lines on a common field

kill Kill a process by specifying its PID

killall Kill processes by name

let Perform arithmetic on shell variables

link Create a link to a file

ln Create a symbolic link to afile

local Create a function variable

locate Find files

logname Print current loginname

logout Exit a login shell

look Display lines beginning with a givenstring

lpc Line printer control program

lpr Off line print

lprint Print a file

lprintd Abort a print job

lprintq List the print queue

ls List information aboutfile(s)\


lsof List open files

OPERATING SYSTEMS LAB PAGE 12


m
make Recompile a group ofprograms

man Help manual

mkdir Create new folder(s)

mkfifo Make FIFOs (namedpipes)

mkfile Make a file

mktemp Make a temporary file

more Display output one screen at atime


most Browse or page through a textfile
mount Mount a file system
mtools Manipulate MS-DOS files
mtr Network diagnostics(traceroute/ping)
mv Move or rename files or directories
mmv Mass Move and rename (files)

nc Netcat, read and write data acrossnetworks

netstat Networking connections/stats

nice Set the priority of a command or job

nl Number lines and write files

nohup Run a command immune tohangups

notify-send Send desktop notifications

nslookup Query Internet name servers interactively

open Open a file in its defaultapplication

op Operator access

passwd Modify a user password

paste Merge lines of files

OPERATING SYSTEMS LAB PAGE 13


ping Test a networkconnection

pgrep List processes by name

pkill Kill processes by name

popd Restore the previous value of the

currentdirectorypr Prepare files for printing

printcap Printer capability database

printenv Print environment variables

printf Format and print data

ps Process status

pushd Save and then change the current

directorypv Monitor the progress of data through

apipe

pwd Print Working Directory

quota Display disk usage and

limits quotacheck Scan a file system for

diskusager

ram ram disk device

rar Archive files with compression

rcp Copy files between two machines

read Read a line from standard input

readarray Read from stdin into an array

variablereadonly Mark

variables/functions as readonly reboot

Reboot the system

rename Rename files

renice Alter priority of running

processesremsync Synchronize remote files

OPERATING SYSTEMS LAB PAGE 14


rev Reverse lines of a file

rm Remove files

rmdir Remove folder(s)

screen Multiplex terminal, run remote shells viassh

scp Secure copy (remote file copy)

sdiff Merge two files interactively

sed Stream Editor

select Accept keyboard input

seq Print numericsequences

set Manipulate shell variables andfunctions

sftp Secure File Transfer Program

shift Shift positional parameters


shopt Shell Options
shutdown Shutdown or restart linux

sleep Delay for a specifiedtime

slocate Find files

sort Sort text files

source Run commands from a file '.'

split Split a file into fixed-size pieces

ss Socket Statistics

ssh Secure Shell client (remote loginprogram)

su Substitute user identity

sudo Execute a command as anotheruser

sum Print a checksum for a file

suspend Suspend execution of this shell

OPERATING SYSTEMS LAB PAGE 15


t

tail Output the last part of file

tar Store, list or extract files in anarchive

tee Redirect output to multiple files

test Evaluate a conditionalexpression

time Measure Program running time

timeout Run a command with a time limit

times User and system times

touch Change file timestamps

top List processes running on the system

tput Set terminal-dependent capabilities, color,position

traceroute Trace Route to Host

trap Execute a command when the shell receives a signal•

tr Translate, squeeze, and/or delete characters

true Do nothing, successfully

tsort Topological sort

tty Print filename of terminal onstdin

type Describe a command

ulimit Limit user resources

umask Users file creation mask

umount Unmount a device

Unalias Remove an alias

uniq Uniquify files

units Convert units from one scale to another

until Execute commands (until error)

uptime Show uptime

OPERATING SYSTEMS LAB PAGE 16


useradd Create new user account

userdel Delete a user account

usermod Modify user account

users List users currently logged in

v Verbosely list directory contents (`ls -l -b')

vdir Verbosely list directory contents (`ls -l -b')

vi Text Editor

vmstat Report virtual memory statistics

w Show who is logged on and what they are doing

wait Wait for a process to complete

watch Execute/display a program

periodicallywc Print byte, word, and line counts

whereis Search the user's $path, man pages and source files

for a program
which Search the user's $path for a program
filewhile Execute commands
who Print all usernames currently logged in
whoami Print the current user id and name (`id -
un')
wget Retrieve web pages or files via HTTP, HTTPS or
FTPwrite Send a message to another user
x

xargs Execute utility, passing constructed argument


list(s) xdg-open Open a file or URL in the user's preferred
applicationxz Compress or decompress .xz and .lzma files
yes Print a string until interrupted
zip Package and compress (archive) files.

OPERATING SYSTEMS LAB PAGE 17


. Run a command script in the current shell
!! Run the last command again
### Comment / Remark

OPERATING SYSTEMS LAB PAGE 18


Procedure to connect to LINUX(putty)
Step 1:click on putty icon available on desk top. A window is opened

Step 2:fill in ip address of linux server and click open

Step 3: provide login and password (nothing is displayed on screen while typing password)

Step 4: change the default password at your first login

OPERATING SYSTEMS LAB PAGE 19


WEEK : 1

Practice File handling utilities, Process utilities, Disk utilities,


Networkingcommands, Filters, Text processing utilities and Backup
utilities.

Aim: Practice basic commands of Linux

File handling utilities


Cat Command: cat linux command concatenates files and print it on the standard output.
To Create a new file:
cat > file1.txt
This command creates a new file file1.txt. After typing into the file press
control+d(^d) simultaneously to end the file.

To Append data into the file: To append data into the same file use append operator >> to write
intothefile, else the file will be overwritten (i.e., all of its contents will be erased).
cat >> file1.txt

To display a file: This command displays the data in


thefile.cat file1.txt

To concatenate several files and display:


cat file1.txt file2.txt

The above cat command will concatenate the two files (file1.txt and file2.txt) and it will display
the output in the screen. Some times the output may not fit the monitor screen. In such situation
you canprint those files in a new file or display the file using less command.
cat file1.txt file2.txt | less

To concatenate several files and to transfer the output to anotherfile.


cat file1.txt file2.txt > file3.txt

In the above example the output is redirected to new file file3.txt.


rm COMMAND:
rm linux command is used to remove/delete the file from the directory.
To Remove / Delete a file: Here rm command will remove/delete the
filefile1.txt.rm file1.txt

To delete a directory tree:


rm -ir tmp

OPERATING SYSTEMS LAB PAGE 20


This rm command recursively removes the contents of all subdirectories of the
tmpdirectory,prompting you regarding the removal of each file, and then
removes the tmpdirectory itself.

To remove more files at once: rm command removes file1.txt and file2.txt files at
thesame time.rm file1.txt file2.txt

cd COMMAND: cd command is used to change the directory.

cd linux-command
This command will take you to the sub-directory(linux-command) from its parent directory.
Ex:

cd ..
This will change to the parent-directory from the current working directory/sub-directory.
cd ~
This command will move to the user's home directory which is "/home/username".
cp COMMAND:
cp command copy files from one location to another. If the destination is an existing file, then
the file is overwritten; if the destination is an existing directory, the file is copied into
thedirectory (thedirectory is not overwritten).

Copy two files:


cp file1.txt file2.txt
The above cp command copies the content of file1.txt to file2.txt
Ex:

ls COMMAND:
ls command lists the files and directories under current working directory. Display
rootdirectorycontents:

ls /
lists the contents of root directory.
Display hidden files and
directories:ls -a
lists all entries including hidden files and directories.
Display inode information:
ls –i

OPERATING SYSTEMS LAB PAGE 21


ln COMMAND:
ln command is used to create link to a file (or) directory. It helps to provide soft link for desired files.
Inode will be different for source and destination.
ln -s file1.txt file2.txt
Creates a symbolic link to 'file1.txt' with the name of 'file2.txt'. Here inode for 'file1.txt' and
'file2.txt'will be different.

mkdir command:

rmdir command:

mv command:

diff command:

comm command:

wc command:

OPERATING SYSTEMS LAB PAGE 22


Process utilities:
ps Command:
ps command is used to report the process status. ps is the short name for Process Status.
1. ps: List the current running processes.
Output:
PID TTY TIME CMD
2540 pts/1 00:00:00 bash
2. ps –f : Displays full information about currently running processes.
Output:
UID PID PPID C STIME TTY TIME CMD
nirmala 2540 2536 0 15:31 pts/1 00:00:00 bash
3. kill COMMAND: kill command is used to kill the background process.
Step by Step process:
• Open a process music player or any
file.xmms
press ctrl+z to stop the process.
• To know group id or job id of the background
task.jobs -l
It will list the background jobs with its job id as,
• xmms 3956
• kmail 3467
To kill a job or process.
• kill 3956
kill command kills or terminates the background process xmms.

Disk utilities:
du (abbreviated from disk usage) is a standard Unix program used to estimate file
spaceusage—space used under a particular directory or files on a file system.

$du kt.txt pt.txt /* the first column displayed the file's disk usage */
8 kt.txt
4 pt.txt
Using -h option: As mentioned above, -h option is used to produce the output in
humanreadable format.
$du -h kt.txt pt.txt
8.0K
k
t.txt4.0K
p
t.txt
/*now the output is in human readable format i.e in
Kilobytes */Using -a option
$du -a kartik
8 kartik/kt.txt 4 kartik/thakral.png
4 kartik/pt.txt 4 kartik/thakral
4 kartik/pranjal.png 24 kartik

OPERATING SYSTEMS LAB PAGE 23


/*so with -a option used all the files (under directory kartik) disk usage info is displayed
alongwith the thakral sub-directory */

df command : Report file system disk space usage

$df kt.txt
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/the2 1957124 1512 1955612 1% /snap/core
/* the df only showed the disk usage details of the file system that contains file kt.txt */
//using df without any filename //

$df
/* in this case df displayed the disk usage details of all mounted file systems */
Using -h : This is used to make df command display the output in human-readable format.
//using -h with df//

$df -h kt.txt
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/the2 1.9G 1.5M 1.9G 1% /snap/core
/*this output is easily understandable by the user and all cause of -h option */
Networking
commandsping
The ping command sends an echo request to a host available on the network. Using this
command, you can check if your remote host is responding well or not.
Syntax: $ping hostname or ip-address
The above command starts printing a response after every second. To come out of
thecommand, you can terminate it by pressing CNTRL + C keys.
$ping google.com
PING google.com (74.125.67.100) 56(84) bytes of data.
64 bytes from 74.125.67.100: icmp_seq=1 ttl=54 time=39.4 ms
ftp: ftp stands for File Transfer Protocol. This utility helps you upload and download your
filefrom one computer to another computer.
Syntax $ftp hostname or ip-address
$ftp amrood.com
Connected to amrood.com.
220 amrood.com FTP server (Ver 4.9 Thu Sep 2 20:35:07 CDT
2009)Name (amrood.com:amrood): amrood
331 Password required for
amrood.Password:
230 User amrood
logged in.ftp> dir
200 PORT command successful.
….
ftp> quit
221 Goodbye.

OPERATING SYSTEMS LAB PAGE 24


telnet:
Telnet is a utility that allows a computer user at one site to make a connection, login and
then conduct work on a computer at another site. Once you login using Telnet, you can
perform all the activities on your remotely connected machine.

C:>telnet
amrood.com
Trying...
Connected to
amrood.com.Escape
character is '^]'. login:
amrood
amrood's Password:
***************************************************
***WELCOME TO AMROOD.COM *
***************************************************** $ logout
Connection
closed.C:>
Finger:

The finger command displays information about users on a given host. The host can be
eitherlocal or remote.
Check all the logged-in users on the local machine −
$ finger
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 (62.61.164.115)
Check all the logged-in users on the remote machine –
$ finger @avtar.com
Login Name Tty Idle Login Time
Office amrood pts/0 Jun 25 08:03
(62.61.164.115)
Get the information about a specific user available on the remote machine −
$ finger [email protected]
Ifconfig: Ifconfig is used to configure the network interfaces.
Filters

more COMMAND:
more command is used to display text in the terminal screen. It allows only
backwardmovement.
1. more -c index.txt
Clears the screen before printing the file .
2. more -3 index.txt
Prints first three lines of the given file. Press Enter to display the file line by line.
head COMMAND:
head command is used to display the first ten lines of a file, and also specifies how many
linesto display.
1. head index.php

OPERATING SYSTEMS LAB PAGE 25


This command prints the first 10 lines of 'index.php'.
2. head -5 index.php
The head command displays the first 5 lines of 'index.php'.
3. head -c 5 index.php
The above command displays the first 5 characters of 'index.php'.

tail COMMAND:
tail command is used to display the last or bottom part of the file. By default it displays
last10 lines of a file.
1. tail index.php
It displays the last 10 lines of 'index.php'.
2. tail -2 index.php
It displays the last 2 lines of 'index.php'.
3. tail -n 5 index.php
It displays the last 5 lines of 'index.php'.

4. tail -c 5 index.php
It displays the last 5 characters of 'index.php'.
cut COMMAND:
cut command is used to cut out selected fields of each line of a file. The cut command
usesdelimiters to determine where to split fields.
cut -c1-3
text.txt
Output:
Thi
Cut the first three letters from the above line.
paste COMMAND:
paste command is used to paste the content from one file to another file. It is also used to
setcolumn format for each line.
paste test.txt>test1.txt
Paste the content from 'test.txt' file to 'test1.txt' file.
sort COMMAND:
sort command is used to sort the lines in a text file.
1. sort test.txt
Sorts the 'test.txt'file and prints result in the screen.
2. sort -r test.txt
Sorts the 'test.txt' file in reverse order and prints result in the screen.
uniq
Report or filter out repeated lines in a file.
uniq myfile1.txt > myfile2.txt - Removes duplicate lines in the first file1.txt and outputs
theresults to the second file.
Text processing utilities

echo: display a line of text or echo command prints the given input string to standard output.

OPERATING SYSTEMS LAB PAGE 26


eg. echo I love
Indiaecho
$HOME
wc: print the number of newlines, words, and bytes in
fileseg. wc file1.txt
nl: which lets you number lines in files.
eg. $ nl
file1
1 hi
join- Join command is used for merging the lines of different sorted files based on the
presence of common field into a single line. The second line will be appended at the
end ofthe first line and cursor is placed at the end of line after joining.

$cat file1.txt $cat file2.txt $join file1.txt file2.txt


1 AAYUSH 1 101
2 APAAR 2 102
3 HEMANT 3 103
4 KARTIK 4 104
Grep (Global Regular Expression Searching for a pattern), fgrep and egrep

$ grep ―sales director‖ emp1 emp2

$fgrep ‗good bad great‘ userfile


$egrep ‗good | bad | great‘ userfile
cat, head, tail, sort, uniq, cut, paste and etc.

Backup utilities
Linux backup and restore can be done using backup commands tar, cpio, dump and restore.
Backup Restore using tar command

tar: tape archive is used for single or multiple files backup and restore on/from a tape or file.
$tar cvf /dev/rmt/0 *
Options: c -> create ; v -> Verbose ; f->file or archive device ; * -> all files and directories .
$tar cvf /home/backup *
Create a tar called backup in home directory, from all file and directories s in the
currentdirectory.
Viewing a tar backup on a tape or file
$tar tvf /dev/rmt/0 ## view files backed up on a tape device.
$tar tvf /home/backup ## view files backed up inside the backup
Note: t option is used to see the table of content in a tar file.

OPERATING SYSTEMS LAB PAGE 27


Extracting tar backup from the tape
$tar xvf /home/backup ## extract / restore files in to current directory.
Note : x option is used to extract the files from tar file. Restoration will go to present
directoryor original backup path depending on relative or absolute path names used for
backup.
Backup restore using cpio command

Using cpio command to backup all the files in current directory to tape.

find . -depth -print | cpio -ovcB > /dev/rmt/0


cpio expects a list of files and find command provides the list, cpio has to put these
file onsome destination and a > sign redirect these files to tape. This can be a file as
well.

Viewing cpio files on a tape

cpio -ivtB < /dev/rmt/0


## Options i -> input ; v->verbose; t-table of content; B-> set I/O block size to 5120 bytes
Restoring a cpio backup
cpio -ivcB < /dev/rmt/0
## Options i -> input ; v->verbose; t-table of content; B-> set I/O block size to 5120 bytes

OPERATING SYSTEMS LAB PAGE 28


WEEK : 2

Aim:-Write a shell script that receives any number of file names as arguments checks if
every argument supplied is a file or directory and reports accordingly. Whenever the
argument is a file it reports no of lines present in it

ALGORITHM:

step 1: if arguments are less than 1 print Enter at least one input file name and goto
step 9Step 2: selects list a file from list of arguments provided in command line
Step 3: check for whether it is directory if yes print is directory and goto
step 9step 4: check for whether it is a regular file if yes goto step 5 else
goto step 8 Step 5: print given name is regular file
step 6: print No of lines in
filestep 7: goto step
step 8: print not a file or a
directorystep 9: stop

Script name: 2a.sh

OPERATING SYSTEMS LAB PAGE 29


Execution:
provide two file names as input one a regular file and other directory
for example abc1.txt a text file as first argument and mrcet a directory as second argument

Expected Output:
[root@localhost sh]# sh 2a.sh
abc1.txtmrcet given name is file:
abc1.txt

No of lines in file are : 7


abc1.txtmrcet is directory
Output:

OPERATING SYSTEMS LAB PAGE 30


WEEK : 3

CPU SCHEDULINGALGORITHMS

A. FIRST COME FIRST SERVE:

AIM: To write a c program to simulate the CPU scheduling algorithm First Come First
Serve(FCFS)

DESCRIPTION:

To calculate the average waiting time using the FCFS algorithm first the waiting time of the first
process is kept zero and the waiting time of the second process is the burst time of the first
process and the waiting time of the third process is the sum of the burst times of the first and the
second process and so on. After calculating all the waiting times the average waiting time is
calculated as the average of all the waiting times. FCFS mainly says first come first serve the
algorithm which camefirst will be served first.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process name and the burst time
Step 4: Setthe waiting of the first process as ‗0‘and its burst time as its turnaround
timeStep 5: for each process in the Ready Q calculate a).Waiting
time (n) = waiting time (n-1) + Burst time (n-1)b).
Turnaroundtime (n)= waiting time(n)+Burst time(n)
Step 6: Calculate
a) Average waiting time = Total waiting Time / Number of process
b) Average Turnaround time = Total Turnaround Time / Number of
processStep 7: Stop the process

SOURCE CODE :

#include<stdio.h>

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

OPERATING SYSTEMS LAB PAGE 31


{
printf("\nEnter Burst Time for Process %d --
", i);scanf("%d", &bt[i]);
}
wt[0] = wtavg = 0;
tat[0] = tatavg =
bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\t PROCESS \t BURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i],
tat[i]);printf("\n Average Waiting Time --%f", wtavg/n);
printf("\n Average Turnaround Time -- %f",
tatavg/n);getch();
}
INPUT:
Enter the number of processes –
3 Enter Burst Time for Process 0
-- 24Enter Burst Time for
Process 1 -- 3 Enter Burst Time
for Process 2 – 3
Expected Output:
PROCESS BURST TIME WAITING TIME TURNAROUND TIME

P0 24 0 24
P1 3 24 27
P2 3 27 30
Average Waiting Time --17.000000
Average Turnaround Time --
27.000000 OUTPUT:

OPERATING SYSTEMS LAB PAGE 32


B. SHORTEST JOB FIRST:

AIM: To write a program to stimulate the CPU scheduling algorithm Shortest job first (Non- Preemption)

DESCRIPTION:

To calculate the average waiting time in the shortest job first algorithm the sorting of the process based
on their burst time in ascending order then calculate the waiting time of each process as the sum of the
bursting times of all the process previous or before to that process.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue

Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time

Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowest to
highest burst time.
Step 5: Set the waiting time of the first process as ‗0‘ and its turnaround time as its burst time.
Step 6: Sort the processes names based on their Burt time
Step 7: For each process in the ready queue, calculate
A) Waiting time(n)= waiting time (n-1) + Burst time (n-1)

B) Turnaround time (n)= waiting time(n)+Burst time(n)


Step 8: Calculate
A)Average waiting time = Total waiting Time / Number of process
a) Average Turnaround time = Total Turnaround Time / Number ofprocessStep 9: Stop
the process
SOURCE CODE :

#include<stdio.h>
#include<conio.h>

main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
for(i=0;i<n;i++) for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
OPERATING SYSTEMS LAB PAGE 33
bt[i]=bt[k];
bt[k]=temp
;
temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
getch();
}
INPUT:
Enter the number of processes --4
Enter Burst Time for Process 0 --6
Enter Burst Time for Process 1 --8
Enter Burst Time for Process 2 --7
Enter Burst Time for Process 3 –3

Expected Output:
PROCESS BURST TIME WAITING TIME TURNAROUND TIME
P0 6 3 9
P1 8 16 24
P2 7 9 16
P3 3 0 3

Average Waiting Time -- 7.000000


Average Turnaround Time -- 13.000000

OUTPUT:

OPERATING SYSTEMS LAB PAGE 34


C.ROUND ROBIN:

AIM: To simulate the CPU scheduling algorithm round-robin.

DESCRIPTION:

To aim is to calculate the average waiting time. There will be a time slice, each process should be
executed within that time-slice and if not it will go to the waiting state so first check whether the
burst time is less than the time-slice. If it is less than it assign the waiting time to the sum of the total
times. If it is greater than the burst-time then subtract the time slot from the actual burst time and
increment it by time-slot and the loop continues until all the processes are completed.

ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue and time quantum (or) time slice
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Calculate the no. of time slices for each process where No. of time slice for process (n) = burst
time process (n)/time slice
Step 5: If the burst time is less than the time slice then the no. of time slices =1.
Step 6: Consider the ready queue is a circular Q, calculate
a) Waiting time for process (n) = waiting time of process(n-1)+ burst timeof process(n-1 ) + the
time difference in getting the CPU fromprocess(n-1)
b) Turnaround time for process(n) = waiting time of process(n) + burst time of process(n)+ the time
difference in getting CPU from process(n).
Step 7: Calculate
a)Average waiting time = Total waiting Time / Number of process
a) Average Turnaround time = Total Turnaround Time / Number ofprocessStep 8: Stop the process
SOURCE CODE

#include<stdio.h>

main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
printf("Enter the no of processes -- ");
scanf("%d",&n);for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];

OPERATING SYSTEMS LAB PAGE 35


for(i=1;i<n;i++)
if(max<bu[i]) max=bu[i];
for(j=0;j<(max/t)+1;j++)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i]
;bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i]; awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is --%f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
getch();
}
INPUT:
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 – 3
Enter the size of time slice – 3
Expected Output:
The Average Turnaround time is -- 15.000000
The Average Waiting time is --5.000000

PROCESS BURST TIME WAITING TIME TURNAROUND TIME


1 24 6 30
2 3 3 6
3 3 6 9
OUTPUT:

OPERATING SYSTEMS LAB PAGE 36


D.PRIORITY:
AIM: To write a c program to simulate the CPU scheduling priority algorithm.

DESCRIPTION:

To calculate the average waiting time in the priority algorithm, sort the burst times according to
their priorities and then calculate the average waiting time of the processes. The waiting time
ofeach process is obtained by summing up the burst times of all the previous processes.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst timeStep 4:
Sort the ready queue according to the priority number.
Step 5: Set the waiting of the first process as ‗0‘ and its burst time as its turnaround timeStep 6:
Arrange the processes based on process priority
Step 7: For each process in the Ready Q calculate
a) Waiting time(n)= waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n)= waiting time(n)+Burst time(n)
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process Print theresults in an order.
Step9:Stop

SOURCE CODE :
#include<stdio.h>
#include<stdlib.h>

struct process
{
int process_id;
int burst_time;
int priority;
int waiting_time;
int turnaround_time;
};

void find_waiting_time(struct process[], int, int[]);


void find_turnaround_time(struct process[], int, int[], int[]);

void find_average_time(struct process[], int);

void priority_scheduling(struct process[], int);

int main()
{
int n, i;
OPERATING SYSTEMS LAB PAGE 37
struct process proc[10];

printf("Enter the number of processes: ");


scanf("%d", &n);

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

{
printf("\nEnter the process ID: ");
scanf("%d", &proc[i].process_id);

printf("Enter the burst time: ");


scanf("%d", &proc[i].burst_time);

printf("Enter the priority: ");


scanf("%d", &proc[i].priority);
}

priority_scheduling(proc, n);
return 0;
}

void find_waiting_time(struct process proc[], int n, int wt[])


{
int i;
wt[0] = 0;

for(i = 1; i< n; i++)


{
wt[i] = proc[i - 1].burst_time + wt[i - 1];
}
}

void find_turnaround_time(struct process proc[], int n, int wt[], int tat[])


{
int i;
for(i = 0; i< n; i++)
{
tat[i] = proc[i].burst_time + wt[i];
}
}

void find_average_time(struct process proc[], int n)


{
int wt[10], tat[10], total_wt = 0, total_tat = 0, i;

find_waiting_time(proc, n, wt);
find_turnaround_time(proc, n, wt, tat);

OPERATING SYSTEMS LAB PAGE 38


printf("\nProcess ID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time");

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


{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", proc[i].process_id, proc[i].burst_time, proc[i].priority, wt[i], tat[i]);
}

printf("\nAverage Waiting Time = %f", (float)total_wt/n);

printf("\nAverage Turnaround Time = %f\n", (float)total_tat/n);


}

void priority_scheduling(struct process proc[], int n)


{
int i, j, pos;
struct process temp;
for(i = 0; i< n; i++)
{
pos = i;
for(j = i + 1; j < n; j++)
{
if(proc[j].priority< proc[pos].priority)
pos = j;
}

temp = proc[i];
proc[i] = proc[pos];
proc[pos] = temp;
}

find_average_time(proc, n);
}
INPUT:
Enter the number of processes: 3
Enter the process ID: 1 Enter the burst time: 5 Enter the priority: 2
Enter the process ID: 2 Enter the burst time: 2 Enter the priority: 1
Enter the process ID: 3 Enter the burst time: 4 Enter the priority: 3
Process ID Burst Time Priority Waiting Time Turnaround Time 2 2 1 0 2 1 5 2 2 7 3 4 3 7 11
Average Waiting Time = 3.000000 Average Turnaround Time = 6.666667

OPERATING SYSTEMS LAB PAGE 39


WEEK :4

DEAD LOCK AVOIDANCE

AIM: Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)

DESCRIPTION:
Deadlock is a situation where in two or more competing actions are waiting f or the other to finish, and
thus neither ever does. When a new process enters a system, it must declare the maximum number of
instances of each resource type it needed. This number may exceed the total number of resources in the
system. When the user request a set of resources, the system must determine whether the allocation of
each resources will leave the system in safe state. If it will the resources are allocation; otherwise the
process must wait until some other process release the resources.
Data structures Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj Need: If
Need[I, j]=k, Pi may need k more instances of resource type Rj, Need[I, j]=Max[I, j]- Allocation[I, j];
Safety Algorithm
Work and Finish be the vector of length m and n respectively, Work=Available and Finish[i] =False.
1. Find an i such that both
2. Finish[i] =False Need<=Work If no such I exists go to step 4.
3. work= work + Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state. Resource request
algorithmLet Request i be request vector for the process Pi, If request i=[j]=k, then process
Pi wants k instances of resource type Rj.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the resources are available.

3. Have the system pretend to have allocated the requested resources to process Pi by modifying the
state as follows;
Available=Available-Request I; Allocation I=Allocation +Request I; Need i=Need i- Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is
allocated its resources. However if the state is unsafe, the Pi must wait for Request i and the
oldresource-allocation state is restored.

ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
OPERATING SYSTEMS LAB PAGE 40
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safestate.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety.
9. or not if we allow the request.
10. stop the program.
11. End.
SOURCE CODE :

#include<stdio.h>

int main()
{
/* array will store at most 5 process with 3 resoures if your process or
resources is greater than 5 and 3 then increase the size of array */
int p, c, count = 0, i, j, alc[5][3], max[5][3], need[5][3], safe[5], available[3], done[5], terminate = 0;
printf("Enter the number of process and resources");
scanf("%d %d", & p, & c);
// p is process and c is diffrent resources
printf("enter allocation of resource of all process %dx%d matrix", p, c);
for (i = 0; i < p; i++)
{
for (j = 0; j < c; j++)
{
scanf("%d", & alc[i][j]);
}
}
printf("enter the max resource process required %dx%d matrix", p, c);
for (i = 0; i < p; i++)
{
for (j = 0; j < c; j++)
{
scanf("%d", & max[i][j]);
}
}
printf("enter the available resource");
for (i = 0; i < c; i++)
scanf("%d", & available[i]);

printf("\n need resources matrix are\n");


for (i = 0; i < p; i++)
{
for (j = 0; j < c; j++)
{
need[i][j] = max[i][j] - alc[i][j];
printf("%d\t", need[i][j]);
}
printf("\n");
OPERATING SYSTEMS LAB PAGE 41
}

/* once process execute variable done will stop them for again execution */
for (i = 0; i < p; i++)
{
done[i] = 0;
}
while (count < p)
{
for (i = 0; i < p; i++)
{
if (done[i] == 0)
{
for (j = 0; j < c; j++)
{
if (need[i][j] > available[j])
break;
}
//when need matrix is not greater then available matrix then if j==c will true
if (j == c)
{
safe[count] = i;
done[i] = 1;
/* now process get execute release the resources and add them in available resources */
for (j = 0; j < c; j++)
{
available[j] += alc[i][j];
}
count++;
terminate = 0;
} else {
terminate++;
}
}
}
if (terminate == (p - 1))
{
printf("safe sequence does not exist");
break;
}

}
if (terminate != (p - 1))
{
printf("\n available resource after completion\n");
for (i = 0; i < c; i++)
{
printf("%d\t", available[i]);
}
printf("\n safe sequence are\n");
for (i = 0; i < p; i++)
{
OPERATING SYSTEMS LAB PAGE 42
printf("p%d\t", safe[i]);
}
}

return 0;
}

OPERATING SYSTEMS LAB PAGE 43


Expected Output:

Enter the number of process and resources


53
enter allocation of resource of all process 5x3 matrix
010
200
302
211
002
enter the max resource process required 5x3 matrix
753
322
902
422
533
enter the available resource 3 3 2

need resources matrix are


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

available resource after completion


10 5 7
safe sequence are
p1 p3 p4 p0 p2

OUTPUT:

OPERATING SYSTEMS LAB PAGE 44


DEAD LOCKPREVENTION

AIM: To implement deadlock prevention technique

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

DESCRIPTION

Data structures n-Number of process, m-number of resource types.Available: Available[j]=k, k –


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

ALGORITHM:

1. Start the program.


2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safestate.
7. Else system is not in safety state
8. Stop the process
.

SOURCE CODE :
// Banker's Algorithm
#include<stdio.h>
int main()
{
// P0 , P1 , P2 , P3 , P4 are the Process names here
int n , m , i , j , k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[ 5 ] [ 3 ] = { { 0 , 1 , 0 }, // P0 // Allocation Matrix
OPERATING SYSTEMS LAB PAGE 45
{ 2 , 0 , 0 } , // P1
{ 3 , 0 , 2 } , // P2
{ 2 , 1 , 1 } , // P3
{ 0 , 0 , 2 } } ; // P4
int max[ 5 ] [ 3 ] = { { 7 , 5 , 3 } , // P0 // MAX Matrix
{ 3 , 2 , 2 } , // P1
{ 9 , 0 , 2 } , // P2
{ 2 , 2 , 2 } , // P3
{ 4 , 3 , 3 } } ; // P4
int avail[3] = { 3 , 3 , 2 } ; // Available Resources
int f[n] , ans[n] , ind = 0 ;
for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j] ;
}
int y = 0;
for (k = 0; k < 5; k++){
for (i = 0; i < n; i++){
if (f[i] == 0){
int flag = 0;
for (j = 0; j < m; j++) {
if(need[i][j] > avail[j]){
flag = 1;
break;
}
}
if ( flag == 0 ) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y] ;
f[i] = 1;
}
}
}
}
int flag = 1;
for(int i=0;i<n;i++)
{
if(f[i] == 0)
{
flag = 0;
printf(" The following system is not safe ");
break;
}
}
OPERATING SYSTEMS LAB PAGE 46
if (flag == 1)
{

printf(" Following is the SAFE Sequence \ n ");


for (i = 0; i < n - 1; i++)
printf(" P%d -> " , ans[i]);
printf(" P%d ", ans[n - 1]);
}
return(0);
}

Expected Output:
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2
........................................................
Process execute din 1.33 seconds

OUTPUT:

OPERATING SYSTEMS LAB PAGE 47


WEEK : 5

A. AIM: To Write a C program to simulate the concept of 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 neighbors). 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 neighbor. 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.
PROGRAM:
#include<stdio.h>
void one();
void two();
int tph, philname[20], status[20], howhung, hu[20], cho;
main()
{
int i;
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("\n All are hungry..\nDead lock stage will occur");
printf("\nExiting\n");
}
else
{
for(i=0;i<howhung;i++)
{
printf("Enterphilosopher%dposition:",(i+1));
scanf("%d",&hu[i]);
status[hu[i]]=2;
}
do
{
OPERATING SYSTEMS LAB PAGE 48
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()
{
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]]);
}
}
}
}
}
INPUT:

DINING PHILOSOPHER PROBLEM

OPERATING SYSTEMS LAB PAGE 49


DINING PHILOSOPHER PROBLEM
Enter the total no. of philosophers: 5
How many are hungry : 3
Enterphilosopher1position:2
Enterphilosopher2position:4
Enterphilosopher3position: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 waiting1.One can eat at a time 2.Two can eat at a time 3.Exit

OUTPUT:

OPERATING SYSTEMS LAB PAGE 50


B. AIM: To Write a C program to simulate producer-consumer problem using semaphores.

DESCRIPTION
Producer consumer problem is a synchronization problem. There is a fixed size buffer where the
producer produces items and 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. The producer and consumer must be synchronized, so that the consumer does not
try to consume an item that has not yet been produced.

PROGRAM

#include<stdio.h>

int main()
{
int buffer[10], bufsize, in, out, produce, consume, choice = 0;
in = 0;
out = 0;
bufsize = 10;

while (choice != 3)
{
printf("\n1. Produce \t\n2. Consume \t\n3. Exit");
printf("\n Enter your choice: ");
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;
OPERATING SYSTEMS LAB PAGE 51
}
break;

}
return 0;
}

Expected Output:

1. Produce 2. Consume 3. Exit


Enter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. Exit
Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit
Enter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. Exit
Enter your choice: 3

OUTPUT:

OPERATING SYSTEMS LAB PAGE 52


WEEK :6

A. Aim:- Write a C program that illustrate communication between two process using
namedpipes or FIFO

Algorithm:
Create two processes, one is fifoserver_twoway and another one is fifoclient_twoway.
Algorithm for fifoserver_twoway :
step 1:Start
step 2: Creates a named pipe (using library function mkfifo())
with name ―fifo_twoway‖ in /tmp directory, if not created.
step 3: Opens the named pipe for read and write purposes.
step 4: Here, created FIFO with permissions of read and write for Owner. Read for Group and no
permissions for Others.
step 5: Waits infinitely for a message from the client.
step 6: If the message received from the client is not ―end‖, prints the message and
reverses the string. The reversed string is sent back to the client. If the message is ―end‖,
closes the fifo and ends the process.
step 7:stop.

Algorithm for client :


Step 1: start
Step 2: Opens the named pipe for read and write purposes.
Step 3: Accepts string from the user.
Step 4: Checks, if the user enters ―end‖ or other than ―end‖. Either way, it
sends a message to the server. However, if the string is ―end‖, this closes
the FIFO and also ends the process.
Step 5: If the message is sent as not ―end‖, it waits for the message
(reversed string) from the client and prints the reversed string.
Step 6: Repeats infinitely until the user enters the string ―end‖.
Step 7: stop

Program:

/* Filename: fifoserver_twoway.c */
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define FIFO_FILE "/tmp/fifo_twoway"


void reverse_string(char *);
int main() {

int fd;

char readbuf[80];
char end[10]; int
to_end;

OPERATING SYSTEMS LAB PAGE 53


int read_bytes;

/* Create the FIFO if it does not exist */

mkfifo(FIFO_FILE, S_IFIFO|0640);
strcpy(end, "end");
fd = open(FIFO_FILE, O_RDWR);
while(1) {
read_bytes = read(fd, readbuf, sizeof(readbuf));
readbuf[read_bytes] = '\0';
printf("FIFOSERVER: Received string: \"%s\" and length is %d\n", readbuf,
(int)strlen(readbuf));
to_end = strcmp(readbuf, end);

if (to_end == 0) {
close(fd); break;
}
reverse_string(readbuf);
printf("FIFOSERVER: Sending Reversed String: \"%s\" and length is %d\n", readbuf, (int)
strlen(readbuf));
write(fd, readbuf, strlen(readbuf));
/*
sleep - This is to make sure other process reads this, otherwise this
process would retrieve the message
*/ sleep(2);
}
return 0;
}

void reverse_string(char *str)


{
int last, limit, first;
char temp;
last = strlen(str) - 1;
limit = last/2;
first = 0;

while (first < last) {


temp = str[first];
str[first] = str[last];
str[last] = temp; first++;
last--; }
return;

Expected Output:
FIFOSERVER: Received string: "LINUX IPCs" and length is 10
FIFOSERVER: Sending Reversed String: "sCPI XUNIL" and length is 10
FIFOSERVER: Received string: "Inter Process Communication" and length is 27
FIFOSERVER: Sending Reversed String: "noitacinummoC ssecorP retnI" and length is 27
FIFOSERVER: Received string: "end" and length is 3

OPERATING SYSTEMS LAB PAGE 54


/* Filename: fifoclient_twoway.c */

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#define FIFO_FILE "/tmp/fifo_twoway"
int main() {
int fd;
int end_process;
int stringlen;
int read_bytes;
char readbuf[80];
char end_str[5];
printf("FIFO_CLIENT: Send messages, infinitely, to end enter \"end\"\n");
fd = open(FIFO_FILE, O_CREAT|O_RDWR);
strcpy(end_str, "end");
while (1) {
printf("Enter string: ");
fgets(readbuf, sizeof(readbuf), stdin);
stringlen = strlen(readbuf);
readbuf[stringlen - 1] = '\0';
end_process = strcmp(readbuf, end_str);
//printf("end_process is %d\n", end_process);
if (end_process != 0) {
write(fd, readbuf, strlen(readbuf));
printf("FIFOCLIENT: Sent string: \"%s\" and string length is %d\n", readbuf,(int)strlen(readbuf));
read_bytes = read(fd, readbuf, sizeof(readbuf));
readbuf[read_bytes] = '\0';
printf("FIFOCLIENT: Received string: \"%s\" and length is %d\n", readbuf,(int)strlen(readbuf));
} else {
write(fd, readbuf, strlen(readbuf));
printf("FIFOCLIENT: Sent string: \"%s\" and string length is %d\n", readbuf,(int)strlen(readbuf));
close(fd);
break;
}
}
return 0;
}

Expected Output:
FIFO_CLIENT: Send messages, infinitely, to end enter "end" Enter string: LINUX IPCs
FIFOCLIENT: Sent string: "LINUX IPCs" and string length is 10
FIFOCLIENT: Received string: "sCPI XUNIL" and length is 10 Enter string: Inter Process Communication
FIFOCLIENT: Sent string: "Inter Process Communication" and string length is 27
FIFOCLIENT: Received string: "noitacinummoC ssecorP retnI" and length is 27 Enter string: end
FIFOCLIENT: Sent string: "end" and string length is 3

OPERATING SYSTEMS LAB PAGE 55


OUTPUT:

OPERATING SYSTEMS LAB PAGE 56


B. Aim:-Write a C program that receives a message from message queue and display them

Algorithm:
Step 1:Start
Step 2:Declare a message queue structuretypedef struct msgbuf { long mtype;
char mtext[MSGSZ];
} message_buf;
Mtype =0Retrieve the next message on the queue, regardless of its mtype.
PositiveGet the next message with an mtype equal to the specifiedmsgtyp.

Negative Retrieve the first message on the queue whose mtype fieldisless than or equal to the absolute
value of the msgtyp argument.Usually mtype is set to1 mtext is the data this will be added to the queue.

Step 3:Get the message queue id for the "name" 1234, which was created by the serverkey = 1234

Step 4 : if ((msqid = msgget(key, 0666< 0) Then print error


The msgget() function shall return the message queue identifier associated with the argument key.
Step 5: Receive message from message queue by using msgrcv function

int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, intmsgflg);

#include < sys/msg.h>

(msgrcv(msqid, &rbuf, MSGSZ, 1, 0)msqid: message queue id

&sbuf: pointer to user defined structure MSGSZ: message sizeMessage type: 1

Message flag:The msgflg argument is a bit mask constructed by ORing together zero ormore
of the following flags: IPC_NOWAIT or MSG_EXCEPT or MSG_NOERROR

Step 6:if msgrcv <0 return error


Step 7:otherwise print message sent is
sbuf.mextStep 8:stop
Program:
//IPC_msgq_send.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXSIZE128
void die(char *s)
{

OPERATING SYSTEMS LAB PAGE 57


perror(s);
exit(1);
}
typedef struct msgbuf
{
Long mtype;
Char mtext[MAXSIZE];
};
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
size_t buflen;
key = 1234;
if ((msqid = msgget(key, msgflg )) < 0) //Getthe
message queue ID for the given key
die("msgget");
//Message Type
sbuf.mtype = 1;
printf("Enter a message to add to messagequeue : ");
scanf("%[^\n]",sbuf.mtext);
getchar();
buflen = strlen(sbuf.mtext) + 1 ;
if (msgsnd(msqid,&sbuf,buflen,IPC_NOWAIT) < 0)
{
printf ("%d, %d, %s, %d\n", msqid,sbuf.mtype, sbuf.mtext, buflen);
die("msgsnd");
}
else
printf("Message Sent\n");
exit(0);
}
Program:
//IPC_msgq_rcv.c

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE
128void die(char *s)
{
perror(s);
exit(1);
}

OPERATING SYSTEMS LAB PAGE 58


typedef struct msgbuf
{
Long mtype;
Char mtext[MAXSIZE];
};
main()
{
int msqid;
key_t key;
struct msgbuf rcvbuffer;key = 1234;

if ((msqid = msgget(key, 0666)) < 0)die("msgget()");

//Receive an answer of message type 1.


if (msgrcv(msqid, &rcvbuffer, MAXSIZE, 1, 0) < 0)
die("msgrcv");
printf("%s\n", rcvbuffer.mtext);
exit(0);
}
Expected Output:

OUTPUT:

OPERATING SYSTEMS LAB PAGE 59


WEEK : 7

Aim:-Write a C program that illustrates two processes communicating using Shared memory

Algorithm:-
step1.Start
step 2.Include header files required for the
program are
#include <sys/types.h>
#include<sys/ipc.>
#include<sys/shm.>
#include <unistd.h>
#include <string.h>
#include <errno.h>
step 3.Declare the variable which are required aspid_t pidint *shared /* pointer to the shm */int shmid
step 4. Use shmget function to create shared
memory#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg)
The shmget() function shall return the shared memory identifier associated with key The
argumentkey is equal to IPC_PRIVATE. so that the operating system selects the next
Available key for a newly created shared block of memory. Size
represents size of shared memory block Shmflg shared memory permissions which are
represented by octalinteger shmid = shmget (IPC_PRIVATE, sizeof(int), IPC_CREAT |
0666);
print the shared memory id
step 5.if fork()==0
Then begin
shared = shmat(shmid, (void *) 0, 0)
print the shared variable(shared) *shared=2print
*shared sleep(2)
print *shared
end

step 6.else

begin

shared = shmat(shmid, (void *) 0, 0)print the shared variable(shared) print *shared sleep(1)
*shared=30

printf("Parent value=%d\n", *shared);sleep(5)


shmctl(shmid, IPC_RMID, 0)
end

step 7.stop

Sha.c
#include<sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

OPERATING SYSTEMS LAB PAGE 60


#include <errno.h>
int main(void)
{
pid_t pid;
int *shared; /* pointer to the shm */ int shmid;
shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
printf("Shared MemoryID=%u",shmid);
if (fork() == 0) { /* Child */
/* Attach to shared memory and print the pointer */ shared = shmat(shmid, (void *) 0,
0);printf("Child pointer %u\n", shared);
*shared=1;
printf("Child value=%d\n", *shared);
sleep(2); printf("Child value=%d\n", *shared);
}
else { /* Parent */
/* Attach to shared memory and print the pointer */ shared = shmat(shmid, (void *) 0,
0);printf("Parent pointer %u\n", shared); printf("Parent value=%d\n", *shared); sleep(1);
*shared=42;
printf("Parent value=%d\n", *shared);
sleep(5);shmctl(shmid, IPC_RMID, 0);
}

Expected Output: $ ./a.out


Shared Memory ID=65537Child pointer 3086680064 Child value=1
Shared Memory ID=65537Parent pointer 3086680064 Parent value=1
Parent value=42 Child value=42
OUTPUT:

OPERATING SYSTEMS LAB PAGE 61


WEEK : 8

PAGE REPLACEMENT ALGORITHMS

AIM: To implement FIFO page replacement technique.


a) FIFO b) LRU c) OPTIMAL

DESCRIPTION:

Page replacement algorithms are an important part of virtual memory management and it helps the OS to
decide which memory page can be moved out making space for the currently needed page. However, the
ultimate objective of all page replacement algorithms is to reduce the number of page faults.
FIFO-This is the simplest page replacement algorithm. In this algorithm, the operating system keeps
track of all pages in the memory in a queue, the oldest page is in the front of the queue. When a page
needs to bereplaced page in the front of the queue is selected for removal.
LRU-In this algorithm page will be replaced which is least recently used
OPTIMAL- In this algorithm, pages are replaced which would not be used for the longest duration of
time in the future. This algorithm will give us less page fault when compared to other page replacement
algorithms.

ALGORITHM:
1. Start the process

2. Read number of pages n

3. Read number of pages no

4. Read page numbers into an array a[i]

5. Initialize avail[i]=0 .to check page hit

6. Replace the page with circular queue, while re-placing check page availability in the frame Place

avail[i]=1 if page is placed in theframe Count page faults

7. Print the results.

8. Stop the process

A.FIRST IN FIRST OUTSOURCE CODE :

#include<stdio.h>
#include<conio.h>
int fr[3];
void main()
{
void display();
int i,j,page[12]={2,3,2,1,5,2,4,5,3,2,5,2};
int flag1=0,flag2=0,pf=0,frsize=3,top=0;

OPERATING SYSTEMS LAB PAGE 62


for(i=0;i<3;i++)
{
fr[i]=-1;
}
for(j=0;j<12;j++)
{
flag1=0;
flag2=0;
for(i=0;i<12;i++)
{
if(fr[i]==page[j])
{
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<frsize;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];
flag2=1;
break;
}
}
}
if(flag2==0)
{
fr[top]=page[j];
top++;
pf++;
if(top>=frsize)
top=0;
}
display();
}

printf("Number of page faults : %d ",pf+frsize);


//getch();
}
void display()
{
inti
;
printf("\n");
for(i=0;i<3;i++)
printf("%d\t",fr[i]);
}

OPERATING SYSTEMS LAB PAGE 63


Expected Output:
2 -1 -1
2 3 -1
2 3 -1
2 3 1
5 3 1
5 2 1
5 2 4
5 2 4
3 2 4
3 2 4
3 5 4
3 5 2

Number of page faults: 9

OUTPUT:

OPERATING SYSTEMS LAB PAGE 64


B.LEAST RECENTLY USED

AIM: To implement LRU page replacement technique.


ALGORITHM:

1. Start the process

2. Declare the size

3. Get the number of pages to be inserted

4. Get the value

5. Declare counter and stack

6. Select the least recently used page by counter value

7. Stack them according the selection.

8. Display the values

9. Stop the process.

SOURCE CODE :

#include<stdio.h>

#include<conio.h>

int fr[3];

void main()

void display();

int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];

int index,k,l,flag1=0,flag2=0,pf=0,frsize=3;

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

fr[i]=-1;

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

flag1=0,

flag2=0;

OPERATING SYSTEMS LAB PAGE 65


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

if(fr[i]==p[j])

flag1=1;

flag2=1;

break;

if(flag1==0)

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

if(fr[i]==-1)

fr[i]=p[j];

flag2=1;

break;

if(flag2==0)

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

fs[i]=0;

for(k=j-1,l=1;l<=frsize-1;l++,k--)

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

OPERATING SYSTEMS LAB PAGE 66


{

if(fr[i]==p[k])

fs[i]=1;

}}

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

if(fs[i]==0)

index=i;

fr[index]=p[j];

pf++;

display();

printf("\n no of page faults :%d",pf+frsize);

void display()

int i;

printf("\n");

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

printf("\t%d",fr[i]);

Expected Output:
2 -1 -1
2 3 -1
2 3 -1
2 3 1
2 5 1
2 5 1

OPERATING SYSTEMS LAB PAGE 67


2 5 4

2 5 4

3 5 4
3 5 2
3 5 2
3 5 2
no of page faults :7

OUTPUT:

OPERATING SYSTEMS LAB PAGE 68


C. OPTIMAL

AIM: To implement optimal page replacement technique.

ALGORTHIM:

1. Start Program

2 Read Number Of Pages And Frames

3. Read Each Page Value

4. Search For Page In The Frames

5. If Not Available Allocate Free Frame

6. If No Frames Is Free Repalce The Page With The Page That Is Leastly Used

7. Print Page Number Of Page Faults

8. Stop process.

SOURCE CODE:

/*Program to simulate optimal page replacement */


#include<stdio.h>
#include<conio.>
int fr[3], n, m; void
display
(); void
main()
{
int
i,j,page[20],fs[10];
int
max,found=0,lg[3],index,k,l,flag1=0,flag2=0,pf=0
;float pr;
clrscr();
printf("Enter length of the reference string: ");
scanf("%d",&n);
printf("Enter the reference string: ");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter no of frames:");
scanf("%d",&m);
for(i=0;i<m;i++)
fr[i]=-1;

OPERATING SYSTEMS LAB PAGE 69


pf=m;
for(j=0;j<n;j++)
{
flag1=0;
flag2=0;
for(i=0;i<m;i++)
{
if(fr[i]==page[j])
{
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<m;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];
flag2=1;break;
}
}
}
if(flag2==0)
{
for(i=0;i<m;i++)
lg[i]=0;
for(i=0;i<m;i++)
{
for(k=j+1;k<=n;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-j;
break;
}
}
}
found=0;
for(i=0;i<m;i++)
{
if(lg[i]==0)

OPERATING SYSTEMS LAB PAGE 70


{
index
=i;
found =1;
break;
}
}
if(found==0)
{
max=lg[0];
index=0;
for(i=0;i<m;i++)
{
if(max<lg[i])
{
max=lg[i];
index=i;
}
}
}
fr[index]=page
[j;pf++;
}
display();
}
printf("Number of page faults : %d\n",
pf);
pr=(float)pf/n*100;
printf("Page fault rate = %f \n", pr);
getch();
}
void display()
{
Int i;
for(i=0;i<m;i++)
printf("%d\t",fr[i]);
printf("\n");
}

Expected Output:
Enter length of the reference string: 12
Enter the reference string: 1 2 3 4 1 2 5 1 2 3 4 5
Enter no of frames: 3
1 -1 -1
1 2 -1

OPERATING SYSTEMS LAB PAGE 71


123
124
124
124
125
125
125
325
425
425
Number of page faults : 7 Page fault rate = 58.333332

OUTPUT:

OPERATING SYSTEMS LAB PAGE 72


WEEK : 9

Aim: Write a C program that takes one or more file/directory names as command
lineinput and reports following information
A)File Type B)Number Of Links
C) Time of last Access D) Read, write and execute permissions

Algorithm:
Step 1:start

Step 2:Declare struct stat a

Step 3:read arguments at command line

Step 4: set the status of the argument using stat(argv[i],&a);

Step 5:Check whether the given file is Directory file by using S_ISDIR(a.st_mode) if it is a directory
file

print Directory file Else print is Regular file

Step6: print number of links

Step 7:print last time access

Step 8:Print Read,write and execute permissions

Step 9:stop

Program:

#include<stdio.h>
#include<sys/stat.h>
#include<time.h>
int main(int argc,char *argv[])
{
int i,j; struct
stat a;
for (i=1;i<argc;i++)
{
printf("%s : ",argv[i]); stat(argv[i],&a);
if(S_ISDIR(a.st_mode))
{
printf("is a Directory file\n");
}
else
{
printf("is Regular file\n");
}
printf("Inode Number:%d\n",a.st_ino);
printf("UID:%o\n",a.st_uid);
printf("GID:%o\n",a.st_gid);

OPERATING SYSTEMS LAB PAGE 73


printf("No of Links:%d\n",a.st_nlink);
printf("Last Access time:%s",asctime(localtime(&a.st_atime)));

OUTPUT:

OPERATING SYSTEMS LAB PAGE 74


WEEK : 10

AIM: To Write a C program to simulate disk scheduling algorithms


a)FCFS b) SCAN c) C-SCAN
DESCRIPTION:
One of the responsibilities of the operating system is to use the hardware efficiently. For the disk
drives, meeting this responsibility entails having fast access time and large disk bandwidth. Both the
access time and the bandwidth can be improved by managing the order in which disk I/O requests are
serviced which is called as disk scheduling. 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. In the SCAN algorithm, the disk arm starts at one end, and moves towards
the other end, servicing requests as it reaches each cylinder, until it gets to the other end of the disk. At
the other end, the direction of head movement is reversed, and servicing continues. The head
continuously scans back and forth across the disk. C-SCAN is a variant of SCAN designed to provide
a more uniform wait time. Like SCAN, C-SCAN moves the head from one end of the disk to the other,
servicing requests along the way. When the head reaches the other end, however, it immediately
returns to the beginning of the disk without servicing any requests on the return trip.

PROGRAM:

A) FCFS DISK SCHEDULING ALGORITHM

#include<stdio.h>

#include<stdlib.h>

int main()

int RQ[100],i,n,TotalHeadMoment=0,initial;

printf("Enter the number of Requests\n");

scanf("%d",&n);

printf("Enter the Requests sequence\n");

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

scanf("%d",&RQ[i]);

printf("Enter initial head position\n");

scanf("%d",&initial);

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

OPERATING SYSTEMS LAB PAGE 75


{

TotalHeadMoment=TotalHeadMoment+abs(RQ[i]-initial);

initial=RQ[i];

printf("Total head moment is %d",TotalHeadMoment);

return 0;

INPUT

Enter the number of Request 8

Enter the Requests Sequence 95 180 34 119 11 123 62 64

Enter initial head position 50

Expected Output:

Total head moment is 644

OUTPUT:

OPERATING SYSTEMS LAB PAGE 76


B. SCAN DISK SCHEDULING ALGORITHM

#include<stdio.h>
main()
{
int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;
clrscr();
printf("enter the no of tracks to be traveresed");
scanf("%d'",&n);
printf("enter the position of head");
scanf("%d",&h);
t[0]=0;
t[1]=h;
printf("enter the tracks");
for(i=2;i<n+2;i++)
scanf("%d",&t[i]);
for(i=0;i<n+2;i++)
{
for(j=0;j<(n+2)-i-1;j++)
{
if(t[j]>t[j+1])
{
temp=t[j];
t[j]=t[j+1];
t[j+1]=temp;
}}}
for(i=0;i<n+2;i++)
if(t[i]==h)
j=i;k=i;
p=0;
while(t[j]!=0)
{
atr[p]=t[j];
j--;
p++;
}
atr[p]=t[j];
for(p=k+1;p<n+2;p++,k++)
atr[p]=t[k+1];
for(j=0;j<n+1;j++)
{
if(atr[j]>atr[j+1])
d[j]=atr[j]-atr[j+1];
else

OPERATING SYSTEMS LAB PAGE 77


d[j]=atr[j+1]-atr[j];
sum+=d[j];
}
printf("\nAverage header movements:%f",(float)sum/n);
}

INPUT

enter the no of tracks to be traversed 9


enter the position of head 50
enter the tracks
65
78
23
44
65
76
78
89
75

Expected Output:

Average header movements:-116849760.000000

OUTPUT:

OPERATING SYSTEMS LAB PAGE 78


C. C-SCAN DISK SCHEDULING ALGORITHM

#include<stdio.h>

main()

int t[20], d[20], h, i, j, n, temp, k, atr[20], tot, p, sum=0;

printf("enter the no of tracks to be traveresed");

scanf("%d",&n);

printf("enter the position of head");

scanf("%d",&h);

t[0]=0;

t[1]=h;

printf("enter total tracks");

scanf("%d",&tot);

t[2]=tot-1;

printf("enter the tracks");

for(i=3;i<=n+2;i++)

scanf("%d",&t[i]);

for(i=0;i<=n+2;i++)

for(j=0;j<=(n+2)-i-1;j++)

if(t[j]>t[j+1])

temp=t[j];

t[j]=t[j+1];

t[j+1]=temp;

for(i=0;i<=n+2;i++)

OPERATING SYSTEMS LAB PAGE 79


if(t[i]==h)

j=i;

break;

p=0;

while(t[j]!=tot-1)

atr[p]=t[j];

j++;

p++;

atr[p]=t[j];

p++;

i=0;

while(p!=(n+3) && t[i]!=t[h])

atr[p]=t[i];

i++;

p++;

for(j=0;j<n+2;j++)

if(atr[j]>atr[j+1])

d[j]=atr[j]-atr[j+1];

else

d[j]=atr[j+1]-atr[j];

sum+=d[j];

OPERATING SYSTEMS LAB PAGE 80


printf("total header movements%d",sum);

printf("avg is %f",(float)sum/n);

INPUT:

enter the no of tracks to be traveresed10

enter the position of head100

enter total tracks10

enter the tracks55 58 60 70 18 90 15 01 84 164

Expected Output:

total header movements12590526avg is 1259052.625000

OUTPUT:

OPERATING SYSTEMS LAB PAGE 81

You might also like