OSLab Manual Updated 2
OSLab Manual Updated 2
Lab Manual
NAME: _____________________________________
ID: ________________________________________
SECTION: __________________________________
DEGREE: ___________________________________
IQRA UNIVERSITY,
Operating System
(LIST OF LABS)
Lab #1______________________________________________________________
Introduction to UNIX/LINUX Shell
Lab # 2______________________________________________________________
UNIX/LINUX Shell programming
Variable
Basic Variable
Lab # 3______________________________________________________________
UNIX/LINUX Shell programming
Using Array
Basic Operator
Lab # 4______________________________________________________________
UNIX/LINUX Shell programming
Decision Making
Shell Loop
Loop Control
Shell Function
Lab # 5____________________________________________________________
UNIX/LINUX Shell programming
Shell Substitution
Quoting Mechanisms
I/O Redirection
Man_page Help
Lab # 6____________________________________________________________
Linux File Management.
Lab # 7____________________________________________________________
Linux Directory Management
Lab # 8_____________________________________________________________
Linux File Permission / Access Mode
Lab # 9______________________________________________________________
Lab # 11_____________________________________________________________
Memory Management Techniques
Lab # 12_____________________________________________________________
Memory Management Techniques using Paging.
Lab # 13_____________________________________________________________
Deadlock Management Techniques
Lab # 14_____________________________________________________________
Page Replacement Algorithms
Lab # 15____________________________________________________________
Process Synchronization
Operating System
LAB-1
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
Introduction to UNIX/LINUX Shell
Objective: To Understand UNIX/ LINUX Shell
Introduction:
The shell provides you with an interface to the UNIX system. It gathers input from you
and executes programs based on that input. When a program finishes executing, it
displays that program's output.
A shell is an environment in which we can run our commands, programs, and shell
scripts. There are different flavors of shells, just as there are different flavors of
operating systems. Each flavor of shell has its own set of recognized commands and
functions.
Shell Prompt
The prompt, $, which is called command prompt, is issued by the shell. While the
prompt is displayed, you can type a command.
The shell reads your input after you press Enter. It determines the command you want
executed by looking at the first word of your input. A word is an unbroken set of
characters. Spaces and tabs separate words.
Following is a simple example of date command which displays current date and
time:
$date
Thu Jun 25 08:30:19 MST 2009
You can customize your command prompt using environment variable PS1 explained
in Environment tutorial.
Shell Types
In UNIX there are two major types of shells:
The Bourne shell. If you are using a Bourne-type shell, the default prompt is the $
character.
The C shell. If you are using a C-type shell, the default prompt is the % character.
There are again various subcategories for Bourne Shell which are listed as follows −
C shell ( csh)
The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while he
was at AT&T Bell Labs in New Jersey.
The Bourne shell was the first shell to appear on UNIX systems, thus it is referred to
as "the shell".
The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this
reason, it is the shell of choice for writing scripts to use on several different versions
of UNIX.
In this tutorial, we are going to cover most of the Shell concepts based on Borne
Shell.
Shell Scripts
The basic concept of a shell script is a list of commands, which are listed in the order
of execution. A good shell script will have comments, preceded by a pound sign, #,
describing the steps.
There are conditional tests, such as value A is greater than value B, loops allowing
us to go through massive amounts of data, files to read and store data, and variables
to read and store data, and the script may include functions.
Shell scripts and functions are both interpreted. This means they are not compiled.
We are going to write a many scripts in the next several tutorials. This would be a
simple text file in which we would put our all the commands and several other required
constructs that tell the shell environment what to do and when to do it.
Example Script
Assume we create a test.sh script. Note all the scripts would have .shextension.
Before you add anything else to your script, you need to alert the system that a shell
script is being started. This is done using the shebang construct. For example −
#!/bin/sh
This tells the system that the commands that follow are to be executed by the Bourne
shell. It's called a shebang because the # symbol is called a hash, and the ! symbol
is called a bang.
To create a script containing these commands, you put the shebang line first and then
add the commands −
#!/bin/bash
pwd
ls
Shell Comments
You can put your comments in your script as follows −
#!/bin/bash
# Script follows here:
pwd
ls
Now you save the above content and make this script executable as follows −
$chmod +x test.sh
/home/amrood
index.htm unix-basic_utilities.htm unix-directories.htm
test.sh unix-communication.htm unix-environment.htm
The shell is, after all, a real programming language, complete with variables, control
structures, and so forth. No matter how complicated a script gets, however, it is still
just a list of commands executed sequentially.
Following script use the read command which takes the input from the keyboard and
assigns it as the value of the variable PERSON and finally prints it on STDOUT.
#!/bin/sh
# Script follows here:
$./test.sh
What is your name?
Iqra Uni Student
Hello, Iqra Uni Student
$
Task:
Write Linux bash Shell Script, which will ask and display all information
required to Student admission in Engineering and Sciences University.
.
Operating System
LAB-2
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
UNIX/LINUX Shell programming
A variable is nothing more than a pointer to the actual data. The shell enables you to
create, assign, and delete variables.
Variable Names
The name of a variable can contain only letters ( a to z or A to Z), numbers ( 0 to 9)
or the underscore character ( _).
_UNIVERSITY
TOKEN_A
VAR_1
VAR_2
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
The reason you cannot use other characters such as !,*, or - is that these characters
have a special meaning for the shell.
Defining Variables
Variables are defined as follows −
variable_name=variable_value
For example:
NAME="IU_stuudent"
Above example defines the variable NAME and assigns it the value "IU_Student".
Variables of this type are called scalar variables. A scalar variable can hold only one
value at a time.
The shell enables you to store any value you want in a variable. For example −
VAR1="IU_Student"
VAR2=100
Accessing Values
To access the value stored in a variable, prefix its name with the dollar sign ( $) −
For example, following script would access the value of defined variable NAME and
would print it on STDOUT −
#!/bin/sh
NAME="IU_Student"
echo $NAME
IU_Student
Read-only Variables
The shell provides a way to mark variables as read-only by using the readonly
command. After a variable is marked read-only, its value cannot be changed.
For example, following script would give error while trying to change the value of
NAME −
#!/bin/sh
NAME="IU_Student"
readonly NAME
NAME="New_student"
Unsetting Variables
Unsetting or deleting a variable tells the shell to remove the variable from the list of
variables that it tracks. Once you unset a variable, you would not be able to access
stored value in the variable.
Following is the syntax to unset a defined variable using the unset command −
unset variable_name
Above command would unset the value of a defined variable. Here is a simple
example −
#!/bin/sh
NAME="IU_Student"
unset NAME
echo $NAME
Above example would not print anything. You cannot use the unset command
tounset variables that are marked readonly.
Variable Types
When a shell is running, three main types of variables are present −
Local Variables − A local variable is a variable that is present within the current instance
of the shell. It is not available to programs that are started by the shell. They are set at
command prompt.
Shell Variables − A shell variable is a special variable that is set by the shell and is
required by the shell in order to function correctly. Some of these variables are
environment variables whereas others are local variables.
The following table shows a number of special variables that you can use in
your shell scripts
Variable Description
$n These variables correspond to the arguments with which a script was invoked.
Here n is a positive decimal number corresponding to the position of an argument
(the first argument is $1, the second argument is $2, and so on).
$* All the arguments are double quoted. If a script receives two arguments, $* is
equivalent to $1 $2.
$@ All the arguments are individually double quoted. If a script receives two
arguments, $@ is equivalent to $1 $2.
$$ The process number of the current shell. For shell scripts, this is the process ID
under which they are executing.
Command-Line Arguments
The command-line arguments $1, $2, $3,...$9 are positional parameters, with $0
pointing to the actual command, program, shell script, or function and $1, $2, $3, ...$9
as the arguments to the command.
#!/bin/sh
$./test.sh IU Student
File Name : ./test.sh
First Parameter : IU
Second Parameter : Student
Quoted Values: IU Student
Quoted Values: IU Student
Total Number of Parameters : 2
Both the parameter specifies all command-line arguments but the "$*" special
parameter takes the entire list as one argument with spaces between and the "$@"
special parameter takes the entire list and separates it into separate arguments.
We can write the shell script shown below to process an unknown number of
command-line arguments with either the $* or $@ special parameters −
#!/bin/sh
for TOKEN in $*
do
echo $TOKEN
done
Exit Status
The $? variable represents the exit status of the previous command.
Exit status is a numerical value returned by every command upon its completion. As
a rule, most commands return an exit status of 0 if they were successful, and 1 if they
were unsuccessful.
Some commands return additional exit statuses for particular reasons. For example,
some commands differentiate between kinds of errors and will return various exit
values depending on the specific type of failure.
$./test.sh IU Student
File Name : ./test.sh
First Parameter : IU
Second Parameter : Student
Quoted Values: IU Student
Quoted Values: IU Student
Total Number of Parameters : 2
$echo $?
0
$
Task: Use following variables to write your CV in Linux bash script.
Variable Script Output
$0
$n
$#
$*
$@
$?
$$
$!
Operating System
LAB-3
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
UNIX/LINUX Shell programming
Array, Operator
Shell supports a different type of variable called an array variable that can hold
multiple values at the same time. Arrays provide a method of grouping a set of
variables. Instead of creating a new name for each variable that is required, you can
use a single array variable that stores all the other variables.
All the naming rules discussed for Shell Variables would be applicable while naming
arrays.
Say that you are trying to represent the names of various students as a set of
variables. Each of the individual variables is a scalar variable as follows −
NAME01="Iqra"
NAME02="University"
NAME03="Computer Lab"
NAME04="Engineering Lab"
NAME05="Telecom Lab"
We can use a single array to store all the above mentioned names. Following is the
simplest method of creating an array variable is to assign a value to one of its indices.
This is expressed as follows −
array_name[index]=value
Here array_name is the name of the array, index is the index of the item in the array
that you want to set, and value is the value you want to set for that item.
As an example, the following commands −
NAME[0]="Iqra"
NAME[1]="University"
NAME[2]="Computer Lab"
NAME[3]="Engineering Lab"
If you are using ksh shell the here is the syntax of array initiUniversityzation −
If you are using bash shell the here is the syntax of array initiUniversityzation −
${array_name[index]}
Here array_name is the name of the array, and index is the index of the value to be
accessed. Following is the simplest example −
#!/bin/sh
NAME[0]="Iqra"
NAME[1]="University"
NAME[2]="Computer Lab"
NAME[3]="Engineering Lab"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
$./test.sh
First Index: Iqra
Second Index: University
You can access all the items in an array in one of the following ways −
${array_name[*]}
${array_name[@]}
Here array_name is the name of the array you are interested in. Following is the
simplest example −
#!/bin/sh
NAME[0]="Iqra"
NAME[1]="University"
NAME[2]="Computer Lab"
NAME[3]="Engineering Lab"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"
$./test.sh
First Method: Iqra University Computer Lab Engineering Lab
Second Method: Iqra University Computer Lab Engineering Lab
Operator
There are various operators supported by each shell. Our tutorial is based on default
shell (Bourne) so we are going to cover all the important Bourne Shell operators in
the tutorial.
Arithmetic Operators.
Relational Operators.
Boolean Operators.
String Operators.
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"
Total value : 4
There must be spaces between operators and expressions for example 2+2 is not correct,
where as it should be written as 2 + 2.
Arithmetic Operators
There are following arithmetic operators supported by Bourne Shell.
+ Addition - Adds values on either side of the operator `expr $a + $b` will give 30
- Subtraction - Subtracts right hand operand from left `expr $a - $b` will give -10
hand operand
/ Division - Divides left hand operand by right hand `expr $b / $a` will give 2
operand
% Modulus - Divides left hand operand by right hand `expr $b % $a` will give 0
operand and returns remainder
= Assignment - Assign right operand in left operand a=$b would assign value
of b into a
It is very important to note here that all the conditional expressions would be put inside
square braces with one spaces around them, for example [ $a == $b ] is correct where
as [$a==$b] is incorrect.
Relational Operators:
Bourne Shell supports following relational operators which are specific to numeric
values. These operators would not work for string values unless their value is
numeric.
For example, following operators would work to check a relation between 10 and 20
as well as in between "10" and "20" but not in between "ten" and "twenty".
-eq Checks if the value of two operands are equal or not, if yes then condition [ $a -eq $b ] is
becomes true. not true.
-ne Checks if the value of two operands are equal or not, if values are not [ $a -ne $b ] is
equal then condition becomes true. true.
-gt Checks if the value of left operand is greater than the value of right [ $a -gt $b ] is
operand, if yes then condition becomes true. not true.
-lt Checks if the value of left operand is less than the value of right operand, [ $a -lt $b ] is
if yes then condition becomes true. true.
-ge Checks if the value of left operand is greater than or equal to the value of [ $a -ge $b ] is
right operand, if yes then condition becomes true. not true.
-le Checks if the value of left operand is less than or equal to the value of [ $a -le $b ] is
right operand, if yes then condition becomes true. true.
It is very important to note here that all the conditional expressions would be put inside
square braces with one spaces around them, for example [ $a <= $b ] is correct where
as [$a <= $b] is incorrect.
Boolean Operators
There are following boolean operators supported by Bourne Shell.
! This is logical negation. This inverts a true condition into false and vice [ ! false ] is
versa. true.
-o This is logical OR. If one of the operands is true then condition would be [ $a -lt 20 -o
true. $b -gt 100 ] is
true.
-a This is logical AND. If both the operands are true then condition would be [ $a -lt 20 -a
true otherwise it would be false. $b -gt 100 ] is
false.
String Operators
There are following string operators supported by Bourne Shell.
= Checks if the value of two operands are equal or not, if yes then condition [ $a = $b ] is
becomes true. not true.
!= Checks if the value of two operands are equal or not, if values are not [ $a != $b ] is
equal then condition becomes true. true.
-z Checks if the given string operand size is zero. If it is zero length then it [ -z $a ] is
returns true. not true.
str Check if str is not the empty string. If it is empty then it returns false. [ $a ] is not
false.
Task: Write bash scrip to test all Athematic and logical
operators in Linux
+ : add two
number
- : make
decrement
operator
* : Mutiply
negative and
positive number
/: divide any
number by zero
Less than:
Compare two
value
Greater than:
Compare two
value
EquUniversityty:
Compare two
value
Not equal:
Compare two
value
And: make two
simple and gate
Or: make two input
or gate
LAB-4
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
UNIX/LINUX Shell programming
if...fi statement:
The if...fi statement is the fundamental control statement that allows Shell to make
decisions and execute statements conditionally.
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
Give you attention on the spaces between braces and expression. This space is
mandatory otherwise you would get syntax error.
If expression is a shell command then it would be assumed true if it return 0 after its
execution. If it is a boolean expression then it would be true if it returns true.
Example
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
a is not equal to b
if...else...fi statement:
The if...else...fi statement is the next form of control statement that allows Shell to
execute statements in more controlled way and making decision between two
choices.
Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
a is not equal to b
if...elif...else...fi statement:
The if...elif...fi statement is the one level advance form of control statement that
allows Shell to make correct decision out of several conditions.
Syntax
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
There is nothing special about this code. It is just a series of if statements, where
each if is part of the else clause of the previous statement. Here statement(s) are
executed based on the true condition, if non of the condition is true then else block is
executed.
Example
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
a is less than b
Loops:
Loops are a powerful programming tool that enable you to execute a set of commands
repeatedly. In this tutorial, you would examine the following types of loops available
to shell programmers −
Here Shell command is evaluated. If the resulting value is true, givenstatement(s) are
executed. If command is false then no statement would be not executed and program
would jump to the next line after done statement.
Example
Here is a simple example that uses the while loop to display the numbers zero to nine
−
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
0123456789
Syntax
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words). Each time the for loop executes, the value of the
variable var is set to the next word in the list of words, word1 to wordN.
Example
Here is a simple example that uses for loop to span through the given list of numbers
−
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
0123456789
Following is the example to display all the files starting with .bash and available in
your home. I'm executing this script from my root −
#!/bin/sh
for FILE in $HOME/.bash*
do
echo $FILE
done
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc
The until loop
The while loop is perfect for a situation where you need to execute a set of commands
while some condition is true. Sometimes you need to execute a set of commands
until a condition is true.
Syntax
until command
do
Statement(s) to be executed until command is true
done
Example
Here is a simple example that uses the until loop to display the numbers zero to nine
−
#!/bin/sh
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
0123456789
The select loop provides an easy way to create a numbered menu from which users
can select options. It is useful when you need to ask the user to choose one or more
items from a list of choices.
Syntax
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Here var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words). Each time the for loop executes, the value of the
variable var is set to the next word in the list of words, word1 to wordN.
For every selection a set of commands would be executed with-in the loop. This loop
was introduced in ksh and has been adapted into bash. It is not available in sh.
Example
Here is a simple example to let the user select a drink of choice −
#!/bin/ksh
select DRINK in tea cofee water juice appe all none
do
case $DRINK in
tea|cofee|water|all)
echo "Go to canteen"
;;
juice|appe)
echo "Available at home"
;;
none)
break
;;
*) echo "ERROR: InvUniversityd selection"
;;
esac
done
The menu presented by the select loop looks like the following −
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
#? juice
Available at home
#? none
$
So far you have looked at creating loops and working with loops to accomplish
different tasks. Sometimes you need to stop a loop or skip iterations of the loop.
In this tutorial you will learn following two statements used to control shell loops −
A loop may continue forever due to required condition is not met. A loop that executes
forever without terminating executes an infinite number of times. For this reason, such
loops are called infinite loops.
Example
Here is a simple example that uses the while loop to display the numbers zero to nine
−
#!/bin/sh
a=10
until [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
This loop would continue forever because a is alway greater than or equal to 10 and
it would never become less than 10.
break
The break command can also be used to exit from a nested loop using this format −
break n
Example
Here is a simple example which shows that loop would terminate as soon as a
becomes 5:
#!/bin/sh
a=0
while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
012345
Here is a simple example of nested for loop. This script breaks out of both loops if
var1 equals 2 and var2 equals 0 –
#!/bin/sh
for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done
This will produce following result. In the inner loop, you have a break command with
the argument 2. This indicates that if a condition is met you should break out of outer
loop and ultimately from inner loop as well.
10
15
This statement is useful when an error has occurred but you want to try to execute
the next iteration of the loop.
Syntax
continue
Like with the break statement, an integer argument can be given to the continue
command to skip commands from nested loops.
continue n
Example
The following loop makes use of continue statement which returns from the continue
statement and start processing next statement −
#!/bin/sh
NUMS="1 2 3 4 5 6 7"
Functions
Functions enable you to break down the overall functionUniversityty of a script into
smaller, logical subsections, which can then be called upon to perform their individual
task when it is needed.
Using functions to perform repetitive tasks is an excellent way to create code reuse.
Code reuse is an important part of modern object-oriented programming principles.
Creating Functions
To declare a function, simply use the following syntax −
function_name () {
list of commands
}
The name of your function is function_name, and that's what you will use to call it
from elsewhere in your scripts. The function name must be followed by parentheses,
which are followed by a list of commands enclosed within braces.
Example
Following is the simple example of using function −
#!/bin/sh
When you would execute above script it would produce following result −
$./test.sh
Hello World
$
Following is an example where we pass two parameters Iqra and University and then
we capture and print these parameters in the function.
#!/bin/sh
$./test.sh
Hello World Iqra University
$
If you instead want to just terminate execution of the function, then there is way to
come out of a defined function.
Based on the situation you can return any value from your function using
thereturn command whose syntax is as follows −
return code
Here code can be anything you choose here, but obviously you should choose
something that is meaningful or useful in the context of your script as a whole.
Example
Following function returns a value 1 −
#!/bin/sh
$./test.sh
Hello World Iqra University
Return value is 10
$
Nested Functions
One of the more interesting features of functions is that they can call themselves as
well as call other functions. A function that calls itself is known as a recursive function.
#!/bin/sh
number_two () {
echo "This is now the second function speaking..."
}
Task:
3. Make shell function which can find out that input number is prime
or not
4. Make shell function which can eliminate all odd numbers from
integer array.
5. Make shell function which can find the last three prime number
lesser than 100.
Operating System
LAB-5
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
UNIX/LINUX Shell programming
Shell Substitution:
When performing command substitution make sure that you are using the backquote,
not the single quote character.
Example
Command substitution is generally used to assign the output of a command to a
variable. Each of the following examples demonstrate command substitution −
#!/bin/sh
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
UP=`date ; uptime`
echo "Uptime is $UP"
Form Description
${var:-word} If var is null or unset, word is substituted for var. The value
of var does not change.
${var:+word} If var is set, word is substituted for var. The value of vardoes not
change.
Example
Following is the example to show various states of the above substitution −
#!/bin/sh
unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"
var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"
3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix
Quoting mechanisms:
The Metacharacters
Unix Shell provides various metacharacters which have special meaning while using
them in any Shell Script and causes termination of a word unless quoted.
For example ? matches with a single charater while listing files in a directory and
an * would match more than one characters. Here is a list of most of the shell special
characters (also called metacharacters) −
A character may be quoted (i.e., made to stand for itself) by preceding it with a \.
Example
Following is the example which show how to print a * or a ? −
#!/bin/sh
echo Hello; Word
Hello
./test.sh: line 2: Word: command not found
#!/bin/sh
Hello; Word
#!/bin/sh
I have $1200
Quoting Description
Single quote All special characters between these quotes lose their special meaning.
Double quote Most special characters between these quotes lose their special meaning
with these exceptions:
$
`
\$
\'
\"
\\
Backslash Any character immediately following the backslash loses its special
meaning.
Back Quote Anything in between back quotes would be treated as a command and
would be executed.
The Single Quotes
Consider an echo command that contains many special shell characters −
Putting a backslash in front of each special character is tedious and makes the line
difficult to read −
There is an easy way to quote a large group of characters. Put a single quote ( ') at
the beginning and at the end of the string −
Any characters within single quotes are quoted just as if a backslash is in front of
each character. So now this echo command displays properly.
If a single quote appears within a string to be output, you should not put the whole
string within single quotes instead you whould preceed that using a backslash (\) as
follows −
VAR=IQRA
echo '$VAR owes <-$1500.**>; [ as of (`date +%m/%d`) ]'
So this is not what you wanted to display. It is obvious that single quotes prevent
variable substitution. If you want to substitute variable values and to make invert
commas work as expected then you would need to put your commands in double
quotes as follows −
VAR=IQRA
echo "$VAR owes <-\$1500.**>; [ as of (`date +%m/%d`) ]"
Now this would produce following result −
Double quotes take away the special meaning of all characters except the following
−
Any characters within single quotes are quoted just as if a backslash is in front of
each character. So now this echo command displays properly.
If a single quote appears within a string to be output, you should not put the whole
string within single quotes instead you whould preceed that using a backslash (\) as
follows −
Syntax:
Here is the simple syntax to put any Shell command in between back quotes −
Example
var=`command`
Following would execute date command and produced result would be stored in
DATA variable.
DATE=`date`
echo "Current Date: $DATE"
I/O Redirection
Most Unix system commands take input from your terminal and send the resulting
output back to your terminal. A command normally reads its input from a place called
standard input, which happens to be your terminal by default. Similarly, a command
normally writes its output to standard output, which is also your terminal by default.
Output Redirection
The output from a command normally intended for standard output can be easily
diverted to a file instead. This capability is known as output redirection:
If the notation > file is appended to any command that normally writes its output to
standard output, the output of that command will be written to file instead of your
terminal −
Check following who command which would redirect complete output of the
command in users file.
Notice that no output appears at the terminal. This is because the output has been
redirected from the default standard output device (the terminal) into the specified file.
If you would check users file then it would have complete content −
$ cat users
oko tty01 Sep 12 07:30
ai tty15 Sep 12 13:32
ruth tty21 Sep 12 10:10
pat tty24 Sep 12 13:07
steve tty25 Sep 12 13:03
$
If a command has its output redirected to a file and the file already contains some
data, that data will be lost. Consider this example −
$ echo line 1 > users
$ cat users
line 1
$
You can use >> operator to append the output in an existing file as follows −
Input Redirection
Just as the output of a command can be redirected to a file, so can the input of a
command be redirected from a file. As the greater-than character > is used for output
redirection, the less-than character < is used to redirect the input of a command.
The commands that normally take their input from standard input can have their input
redirected from a file in this manner. For example, to count the number of lines in the
file users generated above, you can execute the command as follows –
$ wc -l users
2 users
$
Here it produces output 2 lines. You can count the number of lines in the file by
redirecting the standard input of the wc command from the file users −
$ wc -l < users
2
$
Note that there is a difference in the output produced by the two forms of the wc
command. In the first case, the name of the file users is listed with the line count; in
the second case, it is not.
In the first case, wc knows that it is reading its input from the file users. In the second
case, it only knows that it is reading its input from standard input so it does not display
file name.
Here Document
A here document is used to redirect input into an interactive shell script or program.
We can run an interactive program within a shell script without user action by
supplying the required input for the interactive program, or interactive shell script.
Here the shell interprets the << operator as an instruction to read input until it finds a
line containing the specified delimiter. All the input lines up to the line containing the
delimiter are then fed into the standard input of the command.
The delimiter tells the shell that the here document has completed. Without it, the
shell continues to read input forever. The delimiter must be a single word that does
not contain spaces or tabs.
You can use here document to print multiple lines using your script as follows −
#!/bin/sh
The following script runs a session with the vi text editor and save the input in the file
test.txt.
#!/bin/sh
filename=test.txt
vi $filename <<EndOfCommands
i
This file was created automatically from
a shell script
^[
ZZ
EndOfCommands
If you run this script with vim acting as vi, then you will likely see output like the
following −
$ sh test.sh
Vim: Warning: Input is not from a terminal
$
After running the script, you should see the following added to the file test.txt −
$ cat test.txt
This file was created automatically from
a shell script
$
Here command is the name of the command you want to execute. The file /dev/null
is a special file that automatically discards all its input.
To discard both output of a command and its error output, use standard redirection
to redirect STDERR to STDOUT −
Here 2 represents STDERR and 1 represents STDOUT. You can display a message
on to STDERR by redirecting STDOUT into STDERR as follows −
Redirection Commands
Following is the complete list of commands which you can use for redirection −
Command Description
pgm < file Program pgm reads its input from file.
<< tag Standard input comes from here through next tag at start of line.
Man_page Help
All the Unix commands come with a number of optional and mandatory options. It is very
common to forget complete syntax of these commands.
Because no one can possibly remember every Unix command and all its options, there has
been online help available since Unix's earliest days.
Unix's version of help files are called man pages. If you know any command name but you
do not know how to use it, then Man Pages are here to help you at every step.
Syntax
Here is the simple command to get the detail of any Unix command while working
with the system −
$man command
Example
Now you imagine any command for which you want to get help. Assuming you want
to know about pwd then you simply need to use the following command −
$man pwd
The above command would open a help for you which would give you complete
information about pwd command. Try it yourself at your command prompt to get more
detail on
You can get complete detail on man command itself using the following command −
$man man
Section Description
SEE ALSO Lists other commands that are directly related to the command in the man page
or closely resembling its functionUniversityty.
BUGS Explains any known issues or bugs that exist with the command or its output
EXAMPLES Common usage examples that give the reader an idea of how the command can
be used.
LAB-6
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
Objective: To understand UNIX/Linux file
management by creating, reading, editing and
writing in file.
All data in UNIX is organized into files. All files are organized into directories. These
directories are organized into a tree-like structure called the filesystem.
When you work with UNIX, one way or another you spend most of your time working
with files. This tutorial would teach you how to create and remove files, copy and
rename them, create links to them etc.
Ordinary Files − An ordinary file is a file on the system that contains data, text, or program
instructions. In this tutorial, you look at working with ordinary files.
Directories − Directories store both special and ordinary files. For users familiar with
Windows or Mac OS, UNIX directories are equivalent to folders.
Special Files − Some special files provide access to hardware such as hard drives, CD-
ROM drives, modems, and Ethernet adapters. Other special files are similar to
Universityases or shortcuts and enable you to access a single file using different names.
Listing Files
To list the files and directories stored in the current directory. Use the following
command −
$ls
$ls
The command ls supports the -l option which would help you to get more information
about the listed files −
$ls -l
total 1962188
First Column: represents file type and permission given on the file. Below is the description
of all type of files.
Second Column: represents the number of memory blocks taken by the file or directory.
Third Column: represents owner of the file. This is the Unix user who created this file.
Fourth Column: represents group of the owner. Every Unix user would have an associated
group.
Sixth Column: represents date and time when this file was created or modified last time.
In the ls -l listing example, every file line began with a d, -, or l. These characters
indicate the type of file that's listed.
Prefix Description
- Regular file, such as an ASCII text file, binary executable, or hard link.
b Block special file. Block input/output device file such as a physical hard drive.
c Character special file. Raw input/output device file such as a physical hard
drive
Meta Characters
Meta characters have special meaning in Unix. For example * and ? are
metacharacters. We use * to match 0 or more characters, a question mark ?matches
with single character.
For Example −
$ls ch*.doc
Displays all the files whose name start with ch and ends with .doc −
Here * works as meta character which matches with any character. If you want to
display all the files ending with just .doc then you can use following command −
$ls *.doc
Hidden Files
An invisible file is one whose first character is the dot or period character (.). UNIX
programs (including the shell) use most of these files to store configuration
information.
$ ls -a
Creating Files
You can use vi editor to create ordinary files on any Unix system. You simply need
to give following command −
$ vi filename
Above command would open a file with the given filename. You would need to press
key i to come into edit mode. Once you are in edit mode you can start writing your
content in the file as below −
Press two keys Shift + ZZ together to come out of the file completely.
Now you would have a file created with filename in the current directory.
$ vi filename
$
Editing Files
You can edit an existing file using vi editor. We would cover this in detail in a separate
tutorial. But in short, you can open existing file as follows −
$ vi filename
Once file is opened, you can come in edit mode by pressing key i and then you can
edit file as you like. If you want to move here and there inside a file then first you need
to come out of edit mode by pressing key esc and then you can use following keys
to move inside a file −
So using above keys you can position your cursor where ever you want to edit. Once
you are positioned then you can use i key to come in edit mode. Edit the file, once
you are done press esc and finally two keys Shift + ZZ together to come out of the
file completely.
$ cat filename
This is unix file....I created it for the first time.....
I'm going to save this content in this file.
$
You can display line numbers by using -b option along with cat command as follows
$ cat -b filename
1 This is unix file....I created it for the first time.....
2 I'm going to save this content in this file.
$
Counting Words in a File
You can use the wc command to get a count of the total number of lines, words, and
characters contained in a file. Following is the simple example to see the information
about above created file .
$ wc filename
2 19 103 filename
$
Third Column: represents total number of bytes in the file. This is actual size of the file.
You can give multiple files at a time to get the information about those file. Here is
simple syntax −
Copying Files:
To make a copy of a file use the cp command. The basic syntax of the command is
$ cp source_file destination_file
$ cp filename copyfile
$
Now you would find one more file copyfile in your current directory. This file would
be exactly same as original file filename.
Renaming Files
To change the name of a file use the mv command. Its basic syntax is −
$ mv old_file new_file
Following is the example which would rename existing file filename to newfile:
$ mv filename newfile
$
The mv command would move existing file completely into new file. So in this case
you would fine only newfile in your current directory.
Deleting Files
To delete an existing file use the rm command. Its basic syntax is −
$ rm filename
Following is the example which would completely remove existing file filename:
$ rm filename
$
stdin − This is referred to as standard input and associated file descriptor is 0. This is also
represented as STDIN. Unix program would read default input from STDIN.
stdout − This is referred to as standard output and associated file descriptor is 1. This is
also represented as STDOUT. Unix program would write default output at STDOUT
stderr − This is referred to as standard error and associated file descriptor is 2. This is
also represented as STDERR. Unix program would write all the error message at
STDERR.
Operating System
LAB-7
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
UNIX/LINUX Directory Management
Objective: To Understand UNIX / Linux Directory management
by Creating, Listining and Removing, Changing and Renaming
Directories.
A directory is a file whose sole job is to store file names and related information. All
files, whether ordinary, special, or directory, are contained in directories.
UNIX uses a hierarchical structure for organizing files and directories. This structure
is often referred to as a directory tree . The tree has a single root node, the slash
character ( /), and all other directories are contained below it.
Home Directory
The directory in which you find yourself when you first login is called your home
directory.
You will be doing much of your work in your home directory and subdirectories that
you'll be creating to organize your files.
You can go in your home directory anytime using the following command −
$cd ~
$
Here ~ indicates home directory. If you want to go in any other user's home directory
then use the following command −
$cd ~username
$
$cd -
$
Absolute/Relative Pathnames
Directories are arranged in a hierarchy with root (/) at the top. The position of any file
within the hierarchy is described by its pathname.
Elements of a pathname are separated by a /. A pathname is absolute if it is described
in relation to root, so absolute pathnames always begin with a /.
/etc/passwd
/users/sjones/chem/notes
/dev/rdsk/Os3
chem/notes
personal/res
To determine where you are within the filesystem hierarchy at any time, enter the
command pwd to print the current working directory −
$pwd
/user0/home/amrood
Listing Directories
To list the files in a directory you can use the following syntax −
$ls dirname
Following is the example to list all the files contained in /usr/local directory −
$ls /usr/local
Creating Directories
Directories are created by the following command −
$mkdir dirname
Here, directory is the absolute or relative pathname of the directory you want to
create. For example, the command −
$mkdir mydir
$
Creates the directory mydir in the current directory. Here is another example −
$mkdir /tmp/test-dir
$
If you give more than one directory on the command line, mkdir creates each of the
directories. For example −
Creates the directories docs and pub under the current directory.
$mkdir /tmp/amrood/test
mkdir: Failed to make directory "/tmp/amrood/test";
No such file or directory
$
In such cases, you can specify the -p option to the mkdir command. It creates all the
necessary directories for you. For example −
$mkdir -p /tmp/amrood/test
$
Removing Directories
Directories can be deleted using the rmdir command as follows −
$rmdir dirname
$
Note − To remove a directory make sure it is empty which means there should not
be any file or sub-directory inside this directory.
Above command removes the directories dirname1, dirname2, and dirname2 if they
are empty. The rmdir command produces no output if it is successful.
Changing Directories
You can use the cd command to do more than change to a home directory: You can
use it to change to any directory by specifying a vUniversityd absolute or relative path.
The syntax is as follows −
$cd dirname
$
Here, dirname is the name of the directory that you want to change to. For example,
the command −
$cd /usr/local/bin
$
Changes to the directory /usr/local/bin. From this directory you can cd to the directory
/usr/home/amrood using the following relative path −
$cd ../../home/amrood
$
Renaming Directories
The mv (move) command can also be used to rename a directory. The syntax is as
follows −
If we enter the command to show a listing of the current working directories files and
use the -a option to list all the files and the -l option provides the long listing, this is
the result.
$ls -la
drwxrwxr-x 4 teacher class 2048 Jul 16 17.56 .
drwxr-xr-x 60 root 1536 Jul 13 14:18 ..
---------- 1 teacher class 4210 May 1 08:27 .profile
-rwxr-xr-x 1 teacher class 1948 May 12 13:42 memo
$
Operating System
LAB-8
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
Linux File Permission/ Access Modes
Objective: Changing permission, access and ownership of file
in UNIX/Linux operating system.
File ownership is an important component of UNIX that provides a secure method for
storing files. Every file in UNIX has the following attributes −
Owner permissions − The owner's permissions determine what actions the owner of the
file can perform on the file.
Group permissions − The group's permissions determine what actions a user, who is a
member of the group that a file belongs to, can perform on the file.
Other (world) permissions − The permissions for others indicate what action all other
users can perform on the file.
$ls -l /home/amrood
-rwxr-xr-- 1 amrood users 1024 Nov 2 00:10 myfile
drwxr-xr--- 1 amrood users 1024 Nov 2 00:10 mydir
Here first column represents different access mode ie. permission associated with a
file or directory.
The permissions are broken into groups of threes, and each position in the group
denotes a specific permission, in this order: read (r), write (w), execute (x) −
The first three characters (2-4) represent the permissions for the file's owner. For example
-rwxr-xr-- represents that owner has read (r), write (w) and execute (x) permission.
The second group of three characters (5-7) consists of the permissions for the group to
which the file belongs. For example -rwxr-xr--represents that group has read (r) and
execute (x) permission but no write permission.
The last group of three characters (8-10) represents the permissions for everyone else.
For example -rwxr-xr-- represents that other world has read (r) only permission.
1. Read
Grants the capability to read ie. view the contents of the file.
2. Write
Grants the capability to modify, or remove the content of the file.
3. Execute
User with execute permissions can run a file as a program.
1. Read
Access to a directory means that the user can read the contents. The user can look
at the filenames inside the directory.
2. Write
Access means that the user can add or delete files to the contents of the directory.
3. Execute
Executing a directory doesn't really make a lot of sense so think of this as a traverse
permission.
A user must have execute access to the bin directory in order to execute ls or cd
command.
Changing Permissions
To change file or directory permissions, you use the chmod (change mode)
command. There are two ways to use chmod: symbolic mode and absolute mode.
Here's an example using testfile. Running ls -1 on testfile shows that the file's
permissions are as follows −
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on testfile,
followed by ls -l so you can see the permission changes −
Each permission is assigned a value, as the following table shows, and the total of
each set of permissions provides a number for that set.
0 No permission ---
Here's an example using testfile. Running ls -1 on testfile shows that the file's
permissions are as follows −
$ls -l testfile
-rwxrwxr-- 1 amrood users 1024 Nov 2 00:10 testfile
Then each example chmod command from the preceding table is run on testfile,
followed by ls -l so you can see the permission changes –
Two commands are available to change the owner and the group of files −
chown − The chown command stands for "change owner" and is used to change the
owner of a file.
chgrp − The chgrp command stands for "change group" and is used to change the group
of a file.
Changing Ownership
The chown command changes the ownership of a file. The basic syntax is as follows
−
The value of user can be either the name of a user on the system or the user id (uid)
of a user on the system.
Following example −
NOTE: The super user, root, has the unrestricted capability to change the ownership
of a any file but normal users can change only the owner of files they own.
The chrgp command changes the group ownership of a file. The basic syntax is as
follows −
The value of group can be the name of a group on the system or the group ID (GID)
of a group on the system.
Following example −
Which shows that the SUID bit is set and that the command is owned by the root. A capital letter S in
the execute position instead of a lowercase s indicates that the execute bit is not set.
If the sticky bit is enabled on the directory, files can only be removed if you are one of the following
users −
The owner of the sticky directory
The owner of the file being removed
The super user, root
To set the SUID and SGID bits for any directory try the following −
$ chmod ug+s dirname
$ ls -l
drwsr-sr-x 2 root root 4096 Jun 19 06:45 dirname
$
Operating System
LAB-9
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
CPU Scheduling Algorithms
TASK 1:
DESCRIPTION
Assume all the processes arrive at the same time.
PROGRAM
#include<stdio.h>
#include<conio.h>
main()
{
int bt[20], wt[20], tat[20], i, n; float wtavg, tatavg;
clrscr();
printf("\nEnter the number of processes -- "); scanf("%d", &n);
for(i=0;i<n;i++)
{
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 \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", 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 -- 3
Enter Burst Time for Process
0 -- 24
Enter Burst Time for Process
1 -- 3
Enter Burst Time for Process
2 -- 3
OUTPUT
TURNAROUND
PROCESS BURST TIME WAITING TIME TIME
P0 24 0 24
P1 3 24 27
P2 3 27 30
Average Waiting Time-- 17.000000
Average Turnaround Time -- 27.000000
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
OUTPUT
TURNAROUND
PROCESS BURST TIMEWAITING TIME TIME
P3 30 3
P0 63 9
P2 79 16
P1 816 24
Average Waiting Time -- 7.000000
Average Turnaround Time -- 13.000000
#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;
clrscr();
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];
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
OUTPUT
The Average Turnaround time is – 15.666667
The Average Waiting time is -- 5.666667
TURNAROUND
PROCESS BURST TIME WAITING TIME TIME
1 24 6 30
2 3 4 7
3 3 7 10
_________________________________________________________________________________
PRIORITY CPU SCHEDULING ALGORITHM
#include<stdio.h>
main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp; float wtavg, tatavg;
clrscr();
printf("Enter the number of processes --- "); scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i); scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++) if(pri[i] > pri[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;
}
wtavg = wt[0] = 0; tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];tat[i] = tat[i-1] + bt[i];
OUTPUT
TURNAROUND
PROCESS PRIORITY BURST TIME WAITING TIME TIME
1 1 1 0 1
4 2 5 1 6
0 3 10 6 16
2 4 2 16 18
3 5 1 18 19
Average Waiting Time is -
-- 8.200000
Average Turnaround
Time is --- 12.000000
TASK2:
DESCRIPTION
Multi-level queue scheduling algorithm is used in scenarios where the processes can
be classified into groups based on property like process type, CPU time, IO access,
memory size, etc. In a multi-level queue scheduling algorithm, there will be 'n' number
of queues, where 'n' is the number of groups the processes are classified into. Each
queue will be assigned a priority and will have its own scheduling algorithm like round-
robin scheduling or FCFS. For the process in a queue to execute, all the queues of
priority higher than it should be empty, meaning the process in those high priority
queues should have completed its execution. In this scheduling algorithm, once
assigned to a queue, the process will not move to any other queues.
PROGRAM
main()
{
int p[20],bt[20], su[20], wt[20],tat[20],i, k, n, temp; float wtavg, tatavg;
clrscr();
printf("Enter the number of processes --- "); scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time of Process %d --- ", i); scanf("%d",&bt[i]);
printf("System/User Process (0/1) ? --- "); scanf("%d", &su[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(su[i] > su[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=su[i];
su[i]=su[k];
su[k]=temp;
}
wtavg = wt[0] = 0; tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];tat[i] = tat[i-1] + bt[i]
INPUT
Enter the number of processes --- 4
Enter the Burst Time of Process 0 --- 3
System/User Process (0/1) ? --- 1
Enter the Burst Time of Process 1 --- 2
System/User Process (0/1) ? --- 0
Enter the Burst Time of Process 2 --- 5
System/User Process (0/1) ? --- 1
Enter the Burst Time of Process 3 --- 1
System/User Process (0/1) ? --- 0
OUTPUT
SYSTEM/USER PROCESS BURST TURNAROUND
PROCESS TIMEWAITING TIMETIME
1 0 2 0 2
3 0 1 23
2 1 5 3 8
0 1 3 811
Average Waiting Time is -
-- 3.250000
Average Turnaround
Time is --- 6.000000
Operating System
LAB-10
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
File Allocation Strategies
Objective:
Write a C program to simulate the following file allocation strategies.
Sequential
Indexed
Linked
TASK1
DESCRIPTION
A file is a collection of data, usually stored on disk. As a logical entity, a file enables to
divide data into meaningful groups. As a physical entity, a file should be considered in
terms of its organization. The term "file organization" refers to the way in which data is
stored in a file and, consequently, the method(s) by which it can be accessed.
struct fileTable
{
char name[20]; int sb, nob;
}ft[30];
void main()
{
int i, j, n; char s[20]; clrscr();
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
break;
if(i==n)
printf("\nFile Not Found");
else
{
printf("\nFILE NAME START BLOCK NO OF BLOCKS BLOCKS OCCUPIED\n");
printf("\n%s\t\t%d\t\t%d\t",ft[i].name,ft[i].sb,ft[i].nob); for(j=0;j<ft[i].nob;j++)
printf("%d, ",ft[i].sb+j);
}
getch();
}
INPUT:
Enter no of files :3
OUTPUT:
START BLOCKS
FILE NAME BLOCK NO OF BLOCKSOCCUPIED
B 102 4 102, 103, 104, 105
struct fileTable
{
char name[20];
int nob;
struct block *sb;
}ft[30];
struct block
{
int bno;
struct block *next;
};
void main()
{
int i, j, n;
char s[20];
struct block *temp;
clrscr();
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter file name %d :",i+1);
scanf("%s",ft[i].name);
printf("Enter no of blocks in file %d :",i+1);
scanf("%d",&ft[i].nob);
ft[i].sb=(struct block*)malloc(sizeof(struct block));
temp = ft[i].sb;
printf("Enter the blocks of the file :");
scanf("%d",&temp->bno);temp->next=NULL;
for(j=1;j<ft[i].nob;j++)
{
temp->next = (struct block*)malloc(sizeof(struct block)); temp = temp->next;
scanf("%d",&temp->bno);
}
temp->next = NULL;
}
printf("\nEnter the file name to be searched -- ");
scanf("%s",s);
for(i=0;i<n;i++)
if(strcmp(s, ft[i].name)==0) break;
if(i==n)
printf("\nFile Not Found");
else
{
printf("\nFILE NAME NO OF BLOCKS BLOCKS OCCUPIED"); printf("\n
%s\t\t%d\t",ft[i].name,ft[i].nob); temp=ft[i].sb;
for(j=0;j<ft[i].nob;j++)
{
printf("%d ",temp->bno);temp = temp->next;
}
}
getch();
}
INPUT:
Enter no of files : 2
Enter file 1 : A
Enter no of blocks in file
1 :4
Enter the blocks of the
file 1 : 12 23 9 4
Enter file 2 : G
Enter no of blocks in file
2 :5
Enter the blocks of the
file 2 : 88 77 66 55 44
Enter the file to be searched :
G
OUTPUT:
FILE NAME NO OF BLOCKS BLOCKS OCCUPIED
struct fileTable
{
char name[20];
int nob, blocks[30];
}ft[30];
void main()
{
int i, j, n; char s[20]; clrscr();
printf("Enter no of files :"); scanf("%d",&n); for(i=0;i<n;i++)
{
printf("\nEnter file name %d :",i+1); scanf("%s",ft[i].name);
printf("Enter no of blocks in file %d :",i+1); scanf("%d",&ft[i].nob);
printf("Enter the blocks of the file :"); for(j=0;j<ft[i].nob;j++)
scanf("%d",&ft[i].blocks[j]);
}
INPUT:
Enter no of files : 2
Enter file 1 : A
Enter no of blocks in file
1 :4
Enter the blocks of the
file 1 : 12 23 9 4
Enter file 2 : G
Enter no of blocks in file
2 :5
Enter the blocks of the
file 2 : 88 77 66 55 44
Enter the file to be searched :
G
OUTPUT:
FILE NAME NO OF BLOCKS BLOCKS OCCUPIED
G 5 88, 77, 66, 55, 44
Operating System
LAB-11
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
Memory Management Techniques
Objective:
Write a C program to simulate the MVT and MFT memory management
techniques.
DESCRIPTION
MFT (Multiprogramming with a Fixed number of Tasks) is one of the old memory
management techniques in which the memory is partitioned into fixed size partitions
and each job is assigned to a partition. The memory assigned to a partition does not
change. MVT (Multiprogramming with a Variable number of Tasks) is the memory
management technique in which each job gets just the amount of memory it needs.
That is, the partitioning of memory is dynamic and changes as jobs enter and leave
the system. MVT is a more ``efficient'' user of resources. MFT suffers with the problem
of internal fragmentation and MVT suffers with external fragmentation.
PROGRAM
main()
{
int ms, bs, nob, ef,n, mp[10],tif=0; int i,p=0;
clrscr();
printf("Enter the total memory available (in Bytes) -- "); scanf("%d",&ms);
printf("Enter the block size (in Bytes) -- "); scanf("%d", &bs);
nob=ms/bs; ef=ms - nob*bs;
printf("\nEnter the number of processes -- "); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter memory required for process %d (in Bytes)-- ",i+1); scanf("%d",&mp[i]);
}
INPUT
Enter the total memory available (in Bytes) -- 1000
Enter the block size (in Bytes)-- 300
Enter the number of processes
–5
Enter memory required for process 1 (in
Bytes) -- 275
Enter memory required for process 2 (in
Bytes) -- 400
Enter memory required for process 3 (in
Bytes) -- 290
Enter memory required for process 4 (in
Bytes) -- 293
Enter memory required for process 5 (in
Bytes) -- 100
OUTPUT
INTERNAL
PROCESS MEMORY REQUIRED ALLOCATED FRAGMENTATION
1 275 YES 25
2 400 NO -----
3 290 YES 10
4 293 YES 7
main()
{
int ms,mp[10],i, temp,n=0; char ch = 'y';
clrscr();
printf("\nEnter the total memory available (in Bytes)-- "); scanf("%d",&ms);
temp=ms;
for(i=0;ch=='y';i++,n++)
{
printf("\nEnter memory required for process %d (in Bytes) -- ",i+1); scanf("%d",&mp[i]);
if(mp[i]<=temp)
{
printf("\nMemory is allocated for Process %d ",i+1); temp = temp - mp[i];
}
else
{
printf("\nMemory is Full"); break;
}
printf("\nDo you want to continue(y/n) -- "); scanf(" %c", &ch);
}
printf("\n\nTotal Memory Available -- %d", ms);
getch();
}
INPUT
Enter the total memory available (in Bytes) -- 1000
Enter memory required for process 1 (in
Bytes) -- 400
Memory is allocated for
Process 1
Do you want to continue(y/n) -- y
Enter memory required for process 2 (in
Bytes) -- 275
Memory is allocated for
Process 2
Do you want to continue(y/n) -- y
Enter memory required for process 3 (in
Bytes) -- 550
OUTPUT
Memory is Full
Total Memory Available -- 1000
DESCRIPTION
One of the simplest methods for memory allocation is to divide memory into
several fixed-sized partitions. Each partition may contain exactly one process. In
this multiple-partition method, when a partition is free, a process is selected from the
input queue and is loaded into the free partition. When the process terminates, the
partition becomes available for another process. The operating system keeps a table
indicating which parts of memory are available and which are occupied. Finally, when
a process arrives and needs memory, a memory section large enough for this process
is provided. When it is time to load or swap a process into main memory, and if there
is more than one free block of memory of sufficient size, then the operating system
must decide which free block to allocate. Best-fit strategy chooses the block that is
closest in size to the request. First-fit chooses the first available block that is large
enough. Worst-fit chooses the largest available block.
PROGRAM
WORST-FIT
#include<stdio.h>
#include<conio.h> #define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp; static int bf[max],ff[max];
clrscr();
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement"); for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
INPUT
Enter the number of blocks: 3 Enter the number of files: 2
BEST-FIT
#include<stdio.h>
#include<conio.h> #define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000; static int bf[max],ff[max];
clrscr();
lowest=temp;
}
}
}
frag[i]=lowest;
bf[ff[i]]=1;
lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock Size\tFragment"); for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
FIRST-FIT
#include<stdio.h>
#include<conio.h> #define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0; static int bf[max],ff[max];
clrscr();
for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i];if(temp>=0)
if(highest<temp)
{
ff[i]=j;
highest=temp;
}
}
}
frag[i]=highest;
bf[ff[i]]=1;
highest=0;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement"); for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
INPUT
Enter the number of blocks: 3
Enter the number of files: 2
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
Objective:
Write a C program to simulate the pagging memory management
techniques.
TASK:
DESCRIPTION
In computer operating systems, paging is one of the memory management schemes
by which a computer stores and retrieves data from the secondary storage for use in
main memory. In the paging memory-managementscheme, the operating system
retrieves data from secondary storage in same-size blocks called pages. Paging is
a memory-management scheme that permits the physical address space a process to
be noncontiguous. The basic method for implementing paging involves breaking
physical memory into fixed-sized blocks called frames and breaking logical memory
into blocks of the same size called pages. When a process is to be executed, its pages
are loaded into any available memory frames from their source.
PROGRAM
#include<stdio.h>
#include<conio.h>
main()
{
int ms, ps, nop, np, rempages, i, j, x, y, pa, offset; int s[10], fno[10][20];
clrscr();
nop = ms/ps;
printf("\nThe no. of pages available in memory are -- %d ",nop);
rempages = nop;
for(i=1;i<=np;i++)
{
if(s[i] >rempages)
{
printf("\nMemory is Full"); break;
}
rempages = rempages - s[i];
printf("\nEnter pagetable for p[%d] --- ",i); for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}
printf("\nEnter Logical Address to find Physical Address "); printf("\nEnter process no. and
pagenumber and offset -- ");
INPUT
Enter the memory size –
1000
Enter the page size -- 100
The no. of pages available in memory are -- 10
Enter number of processes -- 3
Enter no. of pages required for p[1]-- 4
Enter pagetable for p[1] --- 8 6 9 5
OUTPUT
Memory is Full
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
Deadlock Management Techniques
Objective:
Write a C program to simulate Bankers algorithm for the purpose of
deadlock avoidance.
TASK1:
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.
PROGRAM
#include<stdio.h> struct file
{
int all[10]; int max[10]; int need[10]; int flag;
};
void main()
{
struct file f[10]; int fl;
int i, j, k, p, b, n, r, g, cnt=0, id, newr; int avail[10],seq[10];
clrscr();
printf("Enter number of processes -- "); scanf("%d",&n);
printf("Enter number of resources -- "); scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("Enter details for P%d",i); printf("\nEnter allocation\t -- \t"); for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]); printf("Enter Max\t\t -- \t"); for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("\nEnter Available Resources\t -- \t"); for(i=0;i<r;i++)
scanf("%d",&avail[i]);
avail[i]=avail[i] - newr;
}
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];if(f[i].need[j]<0)
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
b=b+1;
else
b=b-1;
}
if(b==r)
{
printf("\nP%d is visited",j); seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<r;k++)
printf("%3d",avail[k]);
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("\n REQUEST NOT GRANTED -- DEADLOCK OCCURRED"); printf("\n SYSTEM IS IN
UNSAFE STATE");
goto y;
}
}
printf("\nSYSTEM IS IN SAFE STATE"); printf("\nThe Safe Sequence is -- ("); for(i=0;i<fl;i++)
printf("P%d ",seq[i]); printf(")");
y:printf("\nProcess\t\tAllocation\t\tMax\t\t\tNeed\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
printf("%6d",f[i].all[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].max[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].need[j]);
printf("\n");
}
getch();
}
INPUT
Enter number of processes – 5
Enter number of resources -- 3
Enter details for P0
Enter allocation -- 0 1 0
Enter Max -- 7 5 3
OUTPUT
P1 is visited( 5 3 2)
P3 is visited( 7 4 3)
P4 is visited( 7 4 5)
P0 is visited( 7 5 5)
P2 is visited( 10 5 7)
SYSTEM IS IN SAFE
STATE
The Safe Sequence is -- (P1 P3 P4 P0
P2 )
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
OUTPUT
Tracks traversed Difference between tracks
55 45
58 3
60 2
70 10
18 52
90 72
Average header
movements:30.888889
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
d[j]=atr[j+1]-atr[j];sum+=d[j];
}
printf("\nAverage header movements:%f",(float)sum/n); getch();
}
INPUT
Enter no.of tracks:9
Enter track position:55 58 60 70 18 90 150 160 184
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; 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 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++)
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];
}
printf("total header movements%d",sum); printf("avg is %f",(float)sum/n);
getch();
}
INPUT
Enter the track position :
55 58 60 70 18 90 150 160 184
Enter starting position :
100
Operating System
LAB-14
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
Page Replacement Algorithms
Objective:
Write a C program to simulate page replacement algorithms
FIFO
LRU
LFU
Write a C program to simulate page replacement algorithms
Optimal
TASK1:
DESCRIPTION
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.
PROGRAM
INPUT
Enter the length of reference string – 20
7012030423032120170
Enter the reference string -- 1
Enter no. of frames -- 3
count[j]=next;
next++;
}
}
if(flag[i]==0)
{
if(i<f)
{
m[i]=rs[i];
count[i]=next;
next++;
}
else
{
min=0;
for(j=1;j<f;j++)
if(count[min] > count[j]) min=j;
m[min]=rs[i];
count[min]=next;
next++;
}
pf++;
}
for(j=0;j<f;j++) printf("%d\t", m[j]);
if(flag[i]==0)
printf("PF No. -- %d" , pf); printf("\n");
}
printf("\nThe number of page faults using LRU are %d",pf); getch();
}
INPUT
Enter the length of reference string -- 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 Enter the number of frames -- 3
main()
{
int rs[50], i, j, k, m, f, cntr[20], a[20], min, pf=0; clrscr();
printf("\nEnter number of page references -- "); scanf("%d",&m);
for(i=0;i<f;i++)
{
cntr[i]=0; a[i]=-1;
}
Printf(“\nThe Page Replacement Process is – \n“); for(i=0;i<m;i++)
{
for(j=0;j<f;j++)
if(rs[i]==a[j])
{
cntr[j]++;
break;
}
if(j==f)
{
min = 0; for(k=1;k<f;k++)
if(cntr[k]<cntr[min])
min=k;
a[min]=rs[i];
cntr[min]=1;
pf++;
}
printf("\n");
for(j=0;j<f;j++)
printf("\t%d",a[j]);
if(j==f)
printf(“\tPF No. %d”,pf);
}
printf("\n\n Total number of page faults -- %d",pf); getch();
}
INPUT
Enter number of page references --
10
Enter the reference string -- 123452525143
Enter the available no. of frames -- 3
TASK2:
DESCRIPTION
Optimal page replacement algorithm has the lowest page-fault rate of all algorithms
and will never suffer from Belady's anomaly. The basic idea is to replace the page that
will not be used for the longest period of time. Use of this page-replacement algorithm
guarantees the lowest possible page fault rate for a fixed number of frames.
Unfortunately, the optimal page-replacement algorithm is difficult to implement,
because it requires future knowledge of the reference string.
PROGRAM
#include<stdio.h> int n;
main()
{
int seq[30],fr[5],pos[5],find,flag,max,i,j,m,k,t,s; int count=1,pf=0,p=0;
float pfr; clrscr();
printf("Enter maximum limit of the sequence: "); scanf("%d",&max);
printf("\nEnter the sequence: "); for(i=0;i<max;i++)
scanf("%d",&seq[i]); printf("\nEnter no. of frames: "); scanf("%d",&n);
fr[0]=seq[0];
pf++;
printf("%d\t",fr[0]);
i=1;
while(count<n)
{
flag=1;
p++;
for(j=0;j<i;j++)
{
if(seq[i]==seq[j])
flag=0;
}
if(flag!=0)
{
fr[count]=seq[i];
printf("%d\t",fr[count]);
count++;
pf++;
}
i++;
}
printf("\n");
for(i=p;i<max;i++)
{
flag=1;
for(j=0;j<n;j++)
{
if(seq[i]==fr[j])
flag=0;
}
if(flag!=0)
{
for(j=0;j<n;j++)
{
m=fr[j];
for(k=i;k<max;k++)
{
if(seq[k]==m)
{
pos[j]=k;
break;
}
else
pos[j]=1;
}
}
for(k=0;k<n;k++)
{
if(pos[k]==1)
flag=0;
}
if(flag!=0)
s=findmax(pos);
if(flag==0)
{
for(k=0;k<n;k++)
{
if(pos[k]==1)
{
s=k;
break;
}
}
}
fr[s]=seq[i];
for(k=0;k<n;k++)
printf("%d\t",fr[k]);
pf++;
printf("\n");
}
}
pfr=(float)pf/(float)max;
printf("\nThe no. of page faults are %d",pf); printf("\nPage fault rate %f",pfr);
getch();
}
int findmax(int a[])
{
int max,i,k=0;
max=a[0];
for(i=0;i<n;i++)
{
if(max<a[i])
{
max=a[i];
k=i;
}
}
return k;
}
INPUT
Enter number of page references --
10
Enter the reference string -- 123452525143
Enter the available no. of frames -- 3
Operating System
LAB-15
Name ____________________
Roll No ___________________
Date ______________________
Marks Obtained ____________
Signature___________________
Process Synchronization
Objective:
1. Write a C program to simulate producer-consumer problem using
semaphores.
TASK1:
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.
12.3PROGRAM
#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: ”);
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
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
TASK2:
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
int tph, philname[20], status[20], howhung, hu[20], cho; 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++)
{
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()
{
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++;
INPUT
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