Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operating System Lab Manual.
1) To make students familiar with Lexical Analysis and Syntax Analysis phases of Compiler Design and implement programs on these phases using LEX & YACC tools and/or C/C++/Java.
2) To enable students to learn different types of CPU scheduling algorithms used in Operating system.
3) To make students able to implement memory management - page replacement and deadlock handling algorithms.
Prof. Chethan Raj C, BE, M.Tech (Ph.D) Dept. of CSE. System Software & Operating System Lab Manual
1. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 1
SYSTEM SOFTWARE AND OPERATING SYSTEM LABORATORY
[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2017 -2018)
SEMESTER – VI
Subject Code 17CSL67 IA Marks 40
Number of Lecture Hours/Week 01I + 02P Exam Marks 60
Total Number of Lecture Hours 40 Exam Hours 03
CREDITS – 02
Course objectives: This laboratory course enables students to
To make students familiar with Lexical Analysis and Syntax Analysis phases of
Compiler Design and implement programs on these phases using LEX & YACC tools
and/or C/C++/Java
To enable students to learn different types of CPU scheduling algorithms used in
Operating system.
To make students able to implement memory management - page replacement and
deadlock handling algorithms
Descriptions (if any)
Exercises to be prepared with minimum three files (Where ever necessary):
i. Header file.
ii. Implementation file.
iii. Application file where main function will be present.
The idea behind using three files is to differentiate between the developer and user sides. In the
developer side, all the three files could be made visible. For the user side only header file and
application files could be made visible, which means that the object code of the implementation
file could be given to the user along with the interface given in the header file, hiding the
source file, if required. Avoid I/O operations (printf/scanf) and use data input file where ever it
is possible
OBJECTIVE:
This laboratory course is intended to make the students experiment on the basic techniques of
compiler construction and tools that can used to perform syntax-directed translation of a high-
level programming language into an executable code.
Students will design and implement language processors in C by using tools to automate parts
of the implementation process.
This will provide deeper insights into the more advanced semantics aspects of programming
languages, code generation, machine independent optimizations, dynamic memory allocation,
and object orientation.
OUTCOMES:
Upon the completion of practical course, the student will be able to:
1. Understand the working of lex and yacc compiler for debugging of programs.
2. Understand and define the role of lexical analyzer, use of regular expression and transition
diagrams.
3. Understand and use Context free grammar, and parse tree construction.
4. Learn & use the new tools and technologies used for designing a compiler.
2. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 2
5. Develop program for solving parser problems.
6. Learn how to write programs that execute faster.
Lab Programs:
1. a) Write a LEX program to recognize valid arithmetic expression. Identifiers in the
expression could be only integers and operators could be + and *. Count the identifiers &
operators present and print them separately.
b) Write YACC program to evaluate arithmetic expression involving operators: +, -, *, and /
2. Develop, Implement and Execute a program using YACC tool to recognize all strings ending
with b preceded by n a‟s using the grammar an b (note: input n value)
3. Design, develop and implement YACC/C program to construct Predictive / LL(1) Parsing
Table for the grammar rules: A aBa , B bB | e. Use this table to parse the sentence: abba$
4. Design, develop and implement YACC/C program to demonstrate Shift Reduce Parsing
technique for the grammar rules: E E+T | T, T T*F | F, F (E) | id and parse the sentence:
id + id * id.
5. Design, develop and implement a C/Java program to generate the machine code using
Triples for the statement A = -B * (C +D) whose intermediate code in three-address form:
T1 = -B
T2 = C + D
T3 = T1 + T2
A = T3
6. a) Write a LEX program to eliminate comment lines in a C program and copy the resulting
program into a separate file.
b) Write YACC program to recognize valid identifier, operators and keywords in the given text
(C program) file.
7. Design, develop and implement a C/C++/Java program to simulate the working of Shortest
remaining time and Round Robin (RR) scheduling algorithms. Experiment with different
quantum sizes for RR algorithm.
8. Design, develop and implement a C/C++/Java program to implement Banker‟s algorithm.
Assume suitable input required to demonstrate the results.
9. Design, develop and implement a C/C++/Java program to implement page replacement
algorithms LRU and FIFO. Assume suitable input required to demonstrate the results.
Course outcomes: The students should be able to:
Implement and demonstrate Lexer‟s and Parser‟s
Evaluate different algorithms required for management, scheduling, allocation and
communication used in operating system.
Conduction of Practical Examination:
All laboratory experiments are to be included for practical examination.
Students are allowed to pick one experiment from the lot.
Strictly follow the instructions as printed on the cover page of answer script
Marks distribution: Procedure + Conduction + Viva:15 + 70 +15 (100)
Change of experiment is allowed only once and marks allotted to the procedure
part to be made zero
3. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 3
Introduction:
Steps to Install LEX and YACC packages in your Ubuntu or any Linux based Operating
system.
PREREQUISITES
A PC installed with Ubuntu or any Linux based OS.(You can also be running Ubuntu
as a virtual machine using VMWare/VirtualBox in Windows OS.
STEPS:
#To run Lex programs (.l extension) user need to install either 'flex' or 'flex-old' package.
#To run Yacc programs (.y extension) user need to install 'bison' package.
Open the 'Terminal' in Linux OS by searching 'Terminal' in the search bar.
To install Lex package:
Type the exact command (either of the two)
sudo apt-get install flex
sudo apt-get install bison
If User may face Error while performing step 1 & 2. Then type the command
sudo apt-get update
Translator Process
Before 1975 writing a compiler was a very time-consuming process. Then Lesk [1975] and
Johnson [1975] published papers on lex and yacc. These utilities greatly simplify compiler
writing.
Implementation details for lex and yacc may be found in Aho [2006]. Flex and bison, clones
for lex and yacc, can be obtained for free from GNU and Cygwin.
Cygwin(interface) is a 32-bit Windows ports of the GNU software. In fact Cygwin is a port
of the Unix operating system to Windows and comes with compilers gcc and g++. To install
simply download and run the setup executable.
Under Unix/ubuntu Operating System install vim editor later install with flex and bison
followed by gcc/g++/gdb to execute Lex and yacc program..
4. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 4
Fig: Compilation Sequence
Introduction to LEX
Lex is a program generator designed for lexical processing of character input streams. It
accepts a high-level, problem oriented specification for character string matching, and
produces a program in a general purpose language which recognizes regular expressions.
The regular expressions are specified by the user in the source specifications given to Lex.
The Lex written code recognizes these expressions in an input stream and partitions the
input stream into strings matching the expressions. At the boundaries between strings
program sections provided by the user are executed. The Lex source file associates the
regular expressions and the program fragments. As each expression appears in the input to
the program written by Lex, the corresponding fragment is executed.
The user supplies the additional code beyond expression matching needed to complete his
tasks, possibly including code written by other generators. The program that recognizes the
expressions is generated in the general purpose programming language employed for the
user's program fragments. Thus, a high level expression language is provided to write the
string expressions to be matched while the user's freedom to write actions is unimpaired.
This avoids forcing the user who wishes to use a string manipulation language for input
analysis to write processing programs in the same and often inappropriate string handling
language.
Lex is not a complete language, but rather a generator representing a new language feature
which can be added to different programming languages, called ``host languages.'' Just as
general purpose languages can produce code to run on different computer hardware, Lex can
write code in different host languages.
Lexical analyzer is build using a tool called LEX. Input is given to LEX and lexical analyzer
is generated.
5. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 5
Lex is a UNIX utility. It is a program generator designed for lexical processing of character
input streams. Lex generates C code for lexical analyzer. It uses the patterns that match
strings in the input and converts the strings to tokens.
Lex helps you by taking a set of descriptions of possible tokens and producing a C routine,
which we call a lexical analyzer. The token descriptions that Lex uses are known as regular
expressions.
LEX Program Structure:
The first section has global C and Lex declarations (regular expressions).
The second section has the patterns (coded in C)
The third section has supplemental C functions. main(), for example,
These sections are delimited by %%.
Lex rules for matching patterns:
The lex rules for matching tokens.
{words} { wordCount++; /*increase the word count by one*/ }
{whitespace} { /* do nothing*/ }
{numbers} { /* one may want to add some processing here*/ }
%%
6. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 6
C code:
The third and final section of programming in Lex covers C function declarations (and
occasionally the main function) Note that this section has to include the yywrap() function.
Lex has a set of functions and variables that are available to the user. One of them is yywrap.
Typically, yywrap() is defined as shown in the example below.
void main()
{
yylex(); /* start the analysis*/
printf(" No of words: %dn", wordCount);
}
int yywrap()
{
return 1;
}
Compiling & Executing Lex Programs:
Lex <flilename.l> => Outputs a C Program
CC lex.yy.c -ll => Outputs a EXE file
./a.out => Executes EXE file
7. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 7
Lex variables
yyin Of the type FILE*. This points to the current file being parsed by the lexer.
yyout Of the type FILE*. This points to the location where the output of the lexer
will be
written. By default, both yyin and yyout point to standard input and output.yytext The text of the matched pattern is stored in this variable (char*).
yyleng Gives the length of the matched pattern.
yylinen Provides current line number information. (May or may not be supported by the
lexer.)
Lex functions
yylex() The function that starts the analysis. It is automatically generated by Lex.
yywrap() This function is called when end of file (or input) is encountered. If this
function returns 1, the parsing stops. So, this can be used to parse multiple
files. Code can be written in the third section, which will allow multiple files
to be parsed. The strategy is to make yyin file pointer (see the preceding
table) point to a different file until all the files are parsed. At the end,
yywrap() can return 1 to indicate end ofparsing.
yyless(int) This function can be used to push back all but first characters of the read
token.
yymore() This function tells the lexer to append the next token to the current token.
Regular Expressions
It is used to describe the pattern. It is widely used to in lex. It uses meta language. The
character used in this Meta language is part of the standard ASCII character set. An
expression is made up of symbols. Normal symbols are characters and numbers, but there are
other symbols that have special meaning in Lex. The following two tables define some of the
symbols used in Lex and give a few typical examples
Pattern Matches
. any character except newline
. literal.
n newline
t tab
^ beginning of line
$ end of line
Fig: Special Characters
8. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 8
Pattern Matches
? zero or one copy of the preceding expression
* zero or more copies of the preceding expression
+ one or more copies of the preceding expression
a|b a or b
(ab)+ one or more copies of ab (grouping)
"a+b" literal "a+b" (C escapes still work)
abc abc
abc* ab abc abcc abccc ...
"abc*" literal abc*
abc+ abc abcc abccc ...
a(bc)+ abc abcbc abcbcbc ...
a(bc)? a abc
Fig: Operators
Pattern Matches
[abc] one of: a b c
[a-z] any letter a-z
[a-z] one of: a - z
[-az] one of: - a z
[A-Za-z0-9]+ one or more alphanumeric characters
[ tn]+ whitespace
[^ab] anything except: a b
[a^b] one of: a ^ b
[a|b] one of: a | b
Fig: Character Class
Character Meaning
A-Z, 0-9, a-z Characters and numbers that form part of the pattern.
. Matches any character except n.
- Used to denote range. Example: A- Z implies all characters from A to
Z.[ ] A character class. Matches any character in the brackets. If the first
character is ^ then it indicates a negation pattern. Example: [abC]
matches either of a, b, and C.
* Match zero or more occurrences of the preceding pattern.
+ Matches one or more occurrences of the preceding pattern.(no empty
string)Ex: [0-9]+ matches ―1‖,‖111‖ or ―123456‖ but not an empty
string.
? Matches zero or one occurrences of the preceding pattern.
Ex: -?[0-9]+ matches a signed number including an optional leading
minus.$ Matches end of line as the last character of the pattern.
9. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 9
{ } 1) Indicates how many times a pattern can be present. Example:
A{1,3} implies
one to three occurrences of A may be present.
2) If they contain name, they refer to a substitution by that name. Ex:
{digit} Used to escape meta characters. Also used to remove the special
meaning of characters as defined in this table.
Ex: n is a newline character, while ―*‖ is a literal asterisk.
^ Negation.
| Matches either the preceding regular expression or the following
regular expression. Ex: cow|sheep|pig matches any of the three words.
"< symbols>" Literal meanings of characters. Meta characters hold.
/ Look ahead. Matches the preceding pattern only if followed by the
succeeding expression. Example: A0/1 matches A0 only if A01 is the
input.
( ) Groups a series of regular expressions together into a new regular
expression. Ex: (01) represents the character sequence 01. Parentheses
are useful when building up complex patterns with *,+ and |
Examples of regular expressions
Regular
expression
Meaning
joke[rs] Matches either jokes or joker.
A{1,2} shis+ Matches AAshis, Ashis, AAshi, Ashi.
(A[b-e])+ Matches zero or one occurrences of A followed by any character
from b to e.[0-9] 0 or 1 or 2 or………9
[0-9]+ 1 or 111 or 12345 or …At least one occurrence ofpreceding exp
[0-9]* Empty string (no digits at all) or one or more occurrence.
-?[0-9]+ -1 or +1 or +2 …..
[0.9]*.[0.9]+ 0.0,4.5 or .31415 But won„t match 0 or 2
Examples of token declarations
Token Associated expression Meaning
number ([0-9])+ 1 or more occurrences
of a digitchars [A-Za- z] Any character
blank " " A blank space
word (chars)+ 1 or more occurrences
of chars
variable (chars)+(number)*(chars)*( number)*
10. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 10
Introduction to YACC (Yet another complier compiler)
YACC provides a general tool for imposing structure on the input to a computer program.
The input specification is a collection of grammar rules. Each rule describes an allowable
structure and gives it a name. YACC prepares a specification of the input process. YACC
generates a function to control the input process. This function is called a parser.
The name is an acronym for ―Yet Another Compiler. YACC generates the code for the parser
in the C programming language. YACC was developed at AT& T for the UNIX operating
system. YACC has also been rewritten for other languages, including JAVA, ADA
The function parser calls the lexical analyzer to pick up the tokens from the input stream.
These tokens are organized according to the input structure rules .The input structure rule is
called as grammar. When one of the rule is recognized, then user code supplied for this rule
(user code is action) is invoked. Actions have the ability to return values and makes use of the
values ofother actions.
Structure of YACC source program:
Basic Specification:
Every YACC specification file consists of three sections. The declarations, Rules (of
grammars), programs. The sections are separated by double percent “%%” marks. The % is
generally used in YACC specification as an escape character.
The general format for the YACC file is very similar to that of the Lex file.
Definition Section
%union It defines the Stack type for the Parser. It is a union of various datas/structures/
objects
%token These are the terminals returned by the yylex function to the YACC. A token
can also have type associated with it for good type checking and syntax
directed translation. A type of a token can be specified as %token <stack
member>tokenName.
Ex: %token NAME NUMBER
11. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 11
%type The type of a non-terminal symbol in the Grammar rule can be specified with
this.The format is %type <stack member>non-terminal.
%noassoc Specifies that there is no associatively of a terminal symbol.
%left Specifies the left associatively of a Terminal Symbol
%right Specifies the right associatively of a Terminal Symbol.
%start Specifies the L.H.S non-terminal symbol of a production rule which should be
taken as the starting point of the grammar rules.
%prec Changes the precedence level associated with a particular rule to that of the
following token name or literal
Rule Section
The rules section simply consists of a list of grammar rules. A grammar rule has the form:
A: BODY
A represents a nonterminal name, the colon and the semicolon are YACC punctuation and
BODY represents names and literals. The names used in the body of a grammar rule may
represent tokens or nonterminal symbols. The literal consists of a character enclosed in single
quotes.
Names representing tokens must be declared as follows in the declaration sections:
%token name1 name2…
Every name not defined in the declarations section is assumed to represent a non-terminal
symbol. Every non-terminal symbol must appear on the left side of at least one rule. Of all
the no terminal symbols, one, called the start symbol has a particular importance. The parser
is designed to recognize the start symbol.
By default the start symbol is taken to be the left hand side of the first grammar rule in the
rules section.With each grammar rule, the user may associate actions to be. These actions
may return values, and may obtain the values returned by the previous actions. Lexical
analyzer can return values for tokens, if desired. An action is an arbitrary C statement.
Actions are enclosed in curly braces.
12. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 12
Compiling & Executing Yacc programs:
Yacc -d <filename.y> => Outputs a C programs
gcc y.tab.h -ly => Outputs a EXE file
./a.out => Executes EXE file
13. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 13
Lex (Scanner), Yacc (Parser):
Fig: Lex and Yacc process
Difference between LEX and YACC
• Lex is used to split the text into a list of tokens, what text become token can be specified
using regular expression in lex file.
• Yacc is used to give some structure to those tokens. For example in Programming
languages, we have assignment statements like int a = 1 + 2; and i want to make sure that the
left hand side of '=' be an identifier and the right side be an expression [it could be more
complex than this]. This can be coded using a CFG rule and this is what you specify in yacc
file and this you cannot do using lex (lexcannot handle recursive languages).
• A typical application of lex and yacc is for implementing programming languages.
• Lex tokenizes the input, breaking it up into keywords, constants, punctuation, etc.
• Yacc then implements the actual computer language; recognizing a for statement, for
instance, or a function definition.
• Lex and yacc are normally used together to construct an application.
• Input Stream (characters) -> Lex (tokens) -> Yacc (Abstract Syntax Tree) -> User
Application
Introduction to Operating Systems
An Operating System is a program that manages the Computer hardware. It controls and
coordinates the use of the hardware among the various application programs for the various
users.
A Process is a program in execution. As a process executes, it changes state
New : The process is being created
Running: Instructions are being executed
Waiting: The process is waiting for some event to occur
Ready : The process is waiting to be assigned to a process
14. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 14
Terminated : The process has finished execution
Apart from the program code, it includes the current activity represented by
Program Counter,
Contents of Processor registers,
Process Stack which contains temporary data like function parameters, return
addresses and local variables
Data section which contains global variables
Heap for dynamic memory allocation
A Multi-programmed system can have many processes running simultaneously with the
CPU multiplexed among them. By switching the CPU between the processes, the OS can
make the computer more productive. There is Process Scheduler which selects the process
among many processes that are ready, for program execution on the CPU. Switching the
CPU to another process requires performing a state save of the current process and a state
restore of new process, this is Context Switch.
Scheduling Algorithms
CPU Scheduler can select processes from ready queue based on various scheduling
algorithms. Different scheduling algorithms have different properties, and the choice of a
particular algorithm may favor one class of processes over another. The scheduling criteria
include
CPU utilization:
Throughput: The number of processes that are completed per unit time.
Waiting time: The sum of periods spent waiting in ready queue.
Turnaround time: The interval between the time of submission of process to the time
of completion.
Response time: The time from submission of a request until the first response is
produced.
The different scheduling algorithms are
FCFS: First Come First Served Scheduling
15. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 15
SJF: Shortest Job First Scheduling
SRTF: Shortest Remaining Time First Scheduling
Priority Scheduling
Round Robin Scheduling
Multilevel Queue Scheduling
Multilevel Feedback Queue Scheduling
Deadlocks
A process requests resources; and if the resource is not available at that time, the process
enters a waiting state. Sometimes, a waiting process is never able to change state, because
the resource is has requested is held by another process which is also waiting. This situation
is called Deadlock. Deadlock is characterized by four necessary conditions
Mutual Exclusion
Hold and Wait
No Preemption
Circular Wait
Deadlock can be handled in one of these ways,
Deadlock Avoidance
Deadlock Detection and Recover
Compiling lex and yacc program
Lex filename.l
Yacc –d filename.y
gcc lex.yy.c y.tab.c –ll –ly
./a.out
Example Programs:
1. Program to count the number of vowels and consonants in a given string.
%{
#include<stdio.h>
int vowels=0;
int cons=0;
%}
%%
[aeiouAEIOU] {vowels++;}
[a-zA-Z] {cons++;}
%%
16. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 16
int yywrap()
{
return 1;
}
main()
{
printf(“Enter the string.. at end press ^dn”);
yylex();
printf(“No of vowels=%dnNo of consonants=%dn”,vowels,cons);
}
2. Program to count the number of characters, words, spaces, end of lines in a given
input file.
%{
#include<stdio.h>
int c=0, w=0, s=0, l=0;
%}
WORD [^ tn,.:]+ EOL [n]
BLANK [ ]
%%
{WORD} {w++; c=c+yyleng;}
{BLANK} {s++;}
{EOL} {l++;}
. {c++;}
%%
int yywrap()
{
return 1;
}
main(int argc, char *argv[])
{
if(argc!=2)
{
printf(“Usage: <./a.out> <sourcefile>n”); exit(0);
}
yyin=fopen(argv[1],”r”);
yylex();
printf(“No of characters=%dnNo of words=%dnNo of spaces=%dn No of
lines=%d”,c,w,s,l);
}
3.Program to count no of:
a)+ve and –ve integers
b)+ve and –ve fractions
17. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 17
%{
#include<stdio.h>
int posint=0, negint=0,posfraction=0, negfraction=0;
%}
%%
[-][0-9]+ {negint++;} [+]?[0-9]+ {posint++;}
[+]?[0-9]*.[0-9]+ {posfraction++;}
[-][0-9]* .[0-9]+ {negfraction++;}
%%
int yywrap()
{
return 1;
}
main(int argc, char *argv[])
{
if(argc!=2)
{
printf(“Usage: <./a.out> <sourcefile>n”); exit(0);
}
yyin=fopen(argv[1],”r”);
yylex();
printf(“No of +ve integers=%dn No of –ve integers=%dn No of +ve fractions=%dn No of –
ve fractions=%dn”, posint, negint, posfraction, negfraction);
}
4. Program to count the no of ‘scanf’ and ‘printf’ statements in a C program. Replace
them with ‘readf’ and ‘writef’ statements respectively.
%{
#include<stdio.h>
int pc=0, sc=0;
%}
%%
“printf” { fprintf(yyout,”writef”); pc++;} “scanf” { fprintf(yyout,”readf”); sc++;}
%%
int yywrap()
{
return 1;
}
main(int argc, char *argv[])
{
if(argc!=2)
{
printf(“Usage: <./a.out> <sourcefile> <destn file>n”); exit(0);
}
18. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 18
yyin=fopen(argv[1],”r”);
yyout=fopen(argv[2],”w”);
yylex();
printf(“No of printf statements = %dn No of scanf statements=%dn”, pc, sc);
}
5. Program to recognize whether a given sentence is simple or compound.
%{
#include<stdio.h>
Int is_simple=1;
%}
%%
[ tn]+[aA][nN][dD][ tn]+ {is_simple=0;}
[ tn]+[oO][rR][ tn]+ {is_simple=0;}
[ tn]+[bB][uU][tT][ tn]+ {is_simple=0;}
. {;}
%%
int yywrap()
{
return 1;
}
main()
{
int k;
printf(“Enter the sentence.. at end press ^d”); yylex();
if(is_simple==1)
{
printf(“The given sentence is simple”);
}
else
{
printf(“The given sentence is compound”);
}
}
6. Program to recognize and count the number of identifiers in a given input file.
%{
#include<stdio.h> int id=0;
%}
%%
[a-zA-Z][a-zA-Z0-9_]* { id++ ; ECHO; printf(“n”);}
.+ { ;} n { ;}
%%
int yywrap()
19. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 19
{
return 1;
}
main (int argc, char *argv[])
{
if(argc!=2)
{
printf(“Usage: <./a.out> <sourcefile>n”); exit(0);
}
yyin=fopen(argv[1],”r”); printf(“Valid identifires aren”); yylex();
printf(“No of identifiers = %dn”,id);
}
YACC PROGRAMS
1. Program to test the validity of a simple expression involving operators +, -, * and /
Lex Part
%{
#include “y.tab.h”
%}
%%
[0-9]+ { return DIGIT; }
[a-zA-Z][a-zA-Z0-9_]* { return ID; }
n { return NL ;}
. { return yytext[0]; }
%%
Yacc Part
%token NUMBER ID NL
%left „+‟ „-„ %left „*‟ „/‟
%%
stmt : exp NL { printf(“Valid Expression”); exit(0);}
;
exp : exp „+‟ exp | exp „-„ exp | exp „*‟ exp | exp „/‟ exp | „(„ exp „)‟
| ID
| NUMBER
;
%%
int yyerror(char *msg)
{
printf(“Invalid Expressionn”); exit(0);
}
main ()
{
printf(“Enter the expressionn”); yyparse();
20. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 20
}
2. Program to check the syntax of a simple expression involving operators +, -, * and /
Lex Part
%{
#include “y.tab.h”
%}
%%
[0-9]+ { return NUMBER; }
[a-zA-Z][a-zA-Z0-9_]* { return ID; }
n { return NL ;}
. { return yytext[0]; }
%%
Yacc Part
%token NUMBER ID NL
%left „+‟ „-„%left „*‟ „/‟
%%
stmt : exp NL { printf(“Valid Expression”); exit(0);}
;
exp : exp „+‟ exp | exp „-„ exp | exp „*‟ exp | exp „/‟ exp | „(„ exp „)‟
| ID
| NUMBER
;
%%
int yyerror(char *msg)
{
printf(“Invalid Expressionn”);
exit(0);
}
main ()
{
printf(“Enter the expressionn”);
yyparse();
}
3. Program to recognize a valid variable, which starts with a letter, followed by any
number of letters or digits.
Yacc Part
%token DIGIT LETTER NL UND
%%
stmt : variable NL { printf(“Valid Identifiersn”); exit(0);} ;
variable : LETTER alphanumeric; alphanumeric: LETTER alphanumeric | DIGIT
alphanumeric
| UND alphanumeric | LETTER
| DIGIT
21. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 21
| UND
;
%%
int yyerror(char *msg)
{
printf(“Invalid Expressionn”); exit(0);
}
main ()
{
printf(“Enter the variable namen”);
yyparse();
}
Lex Part
%{
#include “y.tab.h”
%}
%%
[a-zA-Z] { return LETTER ;}
[0-9] { return DIGIT ; }
[n] { return NL ;}
[_] { return UND; }
. { return yytext[0]; }
%%
4. Program to evaluate an arithmetic expression involving operating +, -, * and /.
Yacc Part
%token NUMBER ID NL
%left „+‟ „-„ %left „*‟ „/‟
%%
stmt : exp NL { printf(“Value = %dn”,$1); exit(0);}
;
exp : exp „+‟ exp { $$=$1+$3; } | exp „-„ exp { $$=$1-$3; } | exp „*‟ exp { $$=$1*$3; } | exp
„/‟ exp { if($3==0)
{
printf(“Cannot divide by 0”); exit(0);
}
else
$$=$1/$3;
}
| „(„ exp „)‟ { $$=$2; }
| ID { $$=$1; }
| NUMBER { $$=$1; }
;
%%
int yyerror(char *msg)
22. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 22
{
printf(“Invalid Expressionn”); exit(0);
}
main ()
{
printf(“Enter the expressionn”);
yyparse();
}
Lex Part
%{
#include “y.tab.h”
extern int yylval;
%}
%%
[0-9]+ { yylval=atoi(yytext); return NUMBER; }
n { return NL ;}
. { return yytext[0]; }
%%
Lab Programs
1. a) a Write a LEX program to recognize valid arithmetic expression. Identifiers in
the expression could be only integers and operators could be + and *. Count the
identifiers & operators present and print them separately.
%{
#include<stdio.h>
int v=0,op=0,id=0,flag=0,IC=0,OC=0,TC=0;
%}
%%
[a-zA-Z]+[0-9A-Za-z]* {id++;printf("n Identifier:");ECHO;IC++;TC++;}
[+-*/=] {op++;printf("n Operartor:");ECHO;OC++;TC++;}
"(" {v++;}
")" {v--;}
";" {flag=1;}
.|n {;}
%%
void main()
{
printf("Enter the expression");
yylex();
if((op+1) ==id && v==0 && flag==0)
{
printf("n Expression is Validn");
23. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 23
printf("nThe total Identifier count is=%dn", IC);
printf("nThe total Operator Count is=%dn", OC);
printf("The total count=%dn",TC);
}
else
{
printf("n Expression is Invalidn");
}
}
OUTPUT: CRC@CRC-OptiPlex-3050:~$ lex 1a.l
CRC@CRC-OptiPlex-3050:~$ gcc lex.yy.c -ll
CRC@CRC-OptiPlex-3050:~$ ./a.out
Enter the expressiona+b
Identifier:a
Operartor:+
Identifier:b
Expression is Valid (ENTER ctrl-D)
The total Identifier count is=2
The total Operator Count is=1
The total count=3
1b)Write YACC program to evaluate arithmetic expression involving operators: +, -, *,
and /.
/*lex Part*/
%{
#include "y.tab.h"
int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return num;} /* convert the string to number and send the
value*/
[+-*/] {return yytext[0];}
[)] { return yytext[0];}
[(] { return yytext[0];}
. {;}
n {return 0;}
%%
/*YACC Part*/
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token num
24. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 24
%left '+' '-'
%left '*' '/'
%%
input:exp {printf("%dn",$$);exit(0);}
exp:exp'+'exp {$$=$1+$3;}
|exp'-'exp{$$=$1-$3;}
|exp'*'exp{$$=$1*$3;}
|exp'/'exp { if($3==0){printf("Divide by Zeron");exit(0);} else
$$=$1/$3;}
|'('exp')'{$$=$2;}
|num{$$=$1;};
%%
int yyerror()
{
printf("error");
exit(0);
}
int main()
{
printf("Enter an expression:n");
yyparse();
}
OUTPUT:
CRC@CRC-OptiPlex-3050:~$ lex 1b.l
CRC@CRC-OptiPlex-3050:~$ yacc -d 1b.y
CRC@CRC-OptiPlex-3050:~$ gcc lex.yy.c y.tab.c -ll -ly
CRC@CRC-OptiPlex-3050:~$ ./a.out
Enter an expression:
a+d
error
CRC@CRC-OptiPlex-3050:~$ ./a.out
Enter an expression:
2+3
5
2) Develop, Implement and execute a program using YACC tool to recognize all strings
ending with b preceded by n a’s using the grammar a n
b (note: input n value).
/*lex Part*/
%{
#include "y.tab.h"
%}
%%
a {return A;}
25. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 25
b {return B;}
[n] return 'n';
%%
//YACC Part
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token A B
%%
input:s'n' {printf("Successful Grammarn");exit(0);}
s: A s1 B| B s1: ; | A s1
%%
main()
{
printf("Enter A Stringn");
yyparse();
}
int yyerror()
{
printf("Error n");
exit(0);
}
OUTPUT:
CRC@CRC-OptiPlex-3050:~$ lex 2.l
CRC@CRC-OptiPlex-3050:~$ yacc -d 2.y
CRC@CRC-OptiPlex-3050:~$ gcc lex.yy.c y.tab.c -ll -ly
CRC@CRC-OptiPlex-3050:~$ ./a.out
enter the string
aab
successful grammar
CRC@CRC-OptiPlex-3050:~$ ./a.out
enter the string
baa
error
3. Design, develop and implement YACC/C program to construct Predictive / LL(1)
Parsing Table for the grammar rules: A →aBa , B →bB | ε. Use this table to parse the
sentence: abba$.
#include<stdio.h>
#include<string.h>
void main()
26. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 26
{
char fin[10][20],st[10][20],ft[20][20],fol[20][20];
int a=0,e,i,t,b,c,n,k,l=0,j,s,m,p;
printf("enter the no. of coordinatesn");
scanf("%d",&n);
printf("enter the productions in a grammarn");
for(i=0;i<n;i++)
scanf("%s",st[i]);
for(i=0;i<n;i++)
fol[i][0]='0';
for(s=0;s<n;s++)
{
for(i=0;i<n;i++)
{
j=3;
l=0;
a=0;
l1:if(!((st[i][j]>64)&&(st[i][j]<91)))
{
for(m=0;m<l;m++)
{
if(ft[i][m]==st[i][j])
goto s1;
}
ft[i][l]=st[i][j];
l=l+1;
s1:j=j+1;
}
else
{
if(s>0)
{
while(st[i][j]!=st[a][0])
{
a++;
}
b=0;
while(ft[a][b]!='0')
{
for(m=0;m<l;m++)
{
if(ft[i][m]==ft[a][b])
goto s2;
}
30. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 30
}
else if(!((st[i][t]>64)&&(st[i][t]<91)))
printf("M[%c,%c]=%sn",st[i][0],st[i][t],fin[s]);
else
{
b=0;
a=0;
while(st[a][0]!=st[i][3])
{
a++;
}
while(ft[a][b]!='0')
{
printf("M[%c,%c]=%sn",st[i][0],ft[a][b],fin[s]);
b++;
}
}
s++;
}
if(st[i][j]=='|')
j++;
}
}
}
Output:CRC@CRC:~/Desktop/finss/sslabcbcs$ vim 3.c
CRC16@CRC:~/Desktop/finss/sslabcbcs$ gcc 3.c
CRC16@CRC:~/Desktop/finss/sslabcbcs$ ./a.out
enter the no. of coordinates
2
enter the productions in a grammar
A->aBa
B->bB|@
first pos
FIRS[A]=a
FIRS[B]=b@
follow pos
FOLLOW[A]=$
FOLLOW[B]=a
M[A,a]=A->aBa
M[B,b]=B->bB
M[B,a]=B->@
CRC16@CRC:~/Desktop/finss/sslabcbcs$ ./a.out
enter the no. of coordinates
3
enter the productions in a grammar
A->aAa|@
B->BA|Ca
31. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 31
C->c
first pos
FIRS[A]=a@
FIRS[B]=c
FIRS[C]=c
follow pos
FOLLOW[A]=$a
FOLLOW[B]=a
FOLLOW[C]=a
M[A,a]=A->aAa
M[A,$]=A->@
M[A,a]=A->@
M[B,c]=B->BA
M[B,c]=B->Ca
M[C,c]=C->c
CRC16@CRC:~/Desktop/finss/sslabcbcs$
4 Design, develop and implement YACC/C program to demonstrate Shift Reduce
Parsing technique for the grammar rules: E →E+T | T, T →T*F | F, F → (E) | id and
parse the sentence: id + id * id.
#include<stdio.h>
#include<string.h>
int k=0,z=0,i=0,j=0,c=0;
char a[16],ac[20],stk[15],act[10];
void check();
void main()
{
puts("GRAMMAR is E->E+E n E->E*E n E->(E) n E->id");
puts("enter input string ");
gets(a);
c=strlen(a);
strcpy(act,"SHIFT->");
puts("stack t input t action");
for(k=0,i=0; j<c; k++,i++,j++)
{
if(a[j]=='i' && a[j+1]=='d')
{
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='0';
a[j]=' ';
a[j+1]=' ';
printf("n$%st%s$t%sid",stk,a,act);
check();
}
33. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 33
printf("n$%st%s$t%s",stk,a,ac);
i=i-2;
}
}
Output:
CRC16@CRC:~/Desktop/finss$ gcc 4.c
CRC16@CRC:~/Desktop/finss$ ./a.out
GRAMMAR is E->E+E
E->E*E
E->(E)
E->id
enter input string
id+id*id
stack input action
$id +id*id$ SHIFT->id
$E +id*id$ REDUCE TO E
$E+ id*id$ SHIFT->symbols
$E+id *id$ SHIFT->id
$E+E *id$ REDUCE TO E
$E *id$ REDUCE TO E
$E* id$ SHIFT->symbols
$E*id $ SHIFT->id
$E*E $ REDUCE TO E
$E $ REDUCE TO E
CRC16@CRC:~/Desktop/finss$ ./a.out
GRAMMAR is E->E+E
E->E*E
E->(E)
E->id
enter input string
id*id
stack input action
$id *id$ SHIFT->id
$E *id$ REDUCE TO E
$E* id$ SHIFT->symbols
$E*id $ SHIFT->id
$E*E $ REDUCE TO E
$E $ REDUCE TO ECRC16@CRC:~/Desktop/finss$ ./a.out
GRAMMAR is E->E+E
E->E*E
E->(E)
E->id
enter input string
id*id+id
stack input action
34. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 34
$id *id+id$ SHIFT->id
$E *id+id$ REDUCE TO E
$E* id+id$ SHIFT->symbols
$E*id +id$ SHIFT->id
$E*E +id$ REDUCE TO E
$E +id$ REDUCE TO E
$E+ id$ SHIFT->symbols
$E+id $ SHIFT->id
$E+E $ REDUCE TO E
$E $ REDUCE TO E
CRC16@CRC:~/Desktop/finss$
5. Design, develop and implement a C/Java program to generate the machine code using
Triples for the statement A = -B * (C +D) whose intermediate code in three-address
form:
T1 = -B
T2 = C + D
T3 = T1 * T2
A = T3
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
char op[2],arg1[5],arg2[5],result[5];
void main()
{
FILE *fp1,*fp2;
fp1=fopen("input.txt","r");
fp2=fopen("output.txt","w");
while(!feof(fp1))
{
fscanf(fp1,"%s%s%s%s",result,arg1,op,arg2);
if(strcmp(op,"+")==0)
{
fprintf(fp2,"nMOV R0,%s",arg1);
fprintf(fp2,"nADD R0,%s",arg2);
fprintf(fp2,"nMOV %s,R0",result);
}
if(strcmp(op,"*")==0)
{
fprintf(fp2,"nMOV R0,%s",arg1);
fprintf(fp2,"nMUL R0,%s",arg2);
fprintf(fp2,"nMOV %s,R0",result);
}
if(strcmp(op,"-")==0)
{
fprintf(fp2,"nMOV R0,%s",arg1);
35. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 35
fprintf(fp2,"nSUB R0,%s",arg2);
fprintf(fp2,"nMOV %s,R0",result);
}
if(strcmp(op,"/")==0)
{
fprintf(fp2,"nMOV R0,%s",arg1);
fprintf(fp2,"nDIV R0,%s",arg2);
fprintf(fp2,"nMOV %s,R0",result);
}
if(strcmp(op,"=")==0)
{
fprintf(fp2,"nMOV R0,%s",arg1);
fprintf(fp2,"nMOV %s,R0",result);
}
}
fclose(fp1);
fclose(fp2);
}
//create and save a output.txt file
//create and save a input.txt file(add content)
Vim input.txt
T1 = -B
T2 = C + D
T3 = T1 * T2 A = T3
output:
CRC16@CRC:~/Desktop/finss$ gcc ic.c
CRC16@CRC:~/Desktop/finss$ ./a.out
Output: Open vim output.txt
MOV R0,C
ADD R0,D
MOV =,R0
MOV R0,A
MOV T2,R0
MOV R0,A
MOV T2,R0
6 a.Write a LEX program to eliminate comment lines in a C program and copy the
resulting program into a separate file.
%{
#include<stdio.h>
int c_count=0;
%}
%%
"/*"[^*/]*"*/" {c_count++;} /*for single and multiple line comments*/
"//".* {c_count++;} /*for single line comments*/
%%
36. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 36
int main( int argc, char **argv)
{
FILE *f1,*f2;
if(argc>1) /*Pass two filenames for execution*/
{
f1=fopen(argv[1],"r");/*open first file for reading*/
if(!f1) /*not able to open file*/
{
printf("file error n");
exit(1);
}
yyin=f1;
f2=fopen(argv[2],"w"); /*open second file for writing*/
if(!f2) /*not able to open file*/
{
printf("Error");
exit(1);
}
yyout=f2;
yylex();
printf("Number of Comment Lines: %dn",c_count);
}
return 0;
}
Output: CRC16@CRC:~/Desktop/finss$ gcc lex.yy.c -ll
CRC16@CRC:~/Desktop/finss$ cat >f1.c
#include<stdio.h>
//hi
void main()
{
/*hi
to all*/
printf("hi1");
}
CRC16@CRC:~/Desktop/finss$ ./a.out f1.c f2.c
Number of Comment Lines: 2
CRC16@CRC:~/Desktop/finss$ vim f2.c
#include<stdio.h>
void main()
{
printf("hi1");
}
CRC@CRC:~$ lex program6.l
CRC@CRC:~$ cc lex.yy.c
CRC@CRC:~$ cat >a.c
37. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 37
#include<stdio.h>
main()
{
int a,b,c;
/* declaration */
printf("------------");
scanf("---------");
// for reading
getch();
}
CRC@CRC:~$ ./a.out a.c b.c
number of comment lines 2
CRC@CRC:~$ cat b.c
#include<stdio.h>
main()
{
int a,b,c;
printf("------------");
scanf("---------");
getch();
}
CRC@CRC:~$ cat >a1.c
main()
{
int a,b,c;
printf("--------------");
// simple comment
scanf("---------") ;
// comment below scanf
getch();
/* multiple
comment */
// single line comment
}
CRC@CRC:~$ ./a.out a1.c b1.c
number of comment lines 4
CRC@CRC:~$ cat b1.c
main()
{
int a,b,c;
printf("--------------");
scanf("---------") ;
getch();
}
38. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 38
6b.Write YACC program to recognize valid identifier, operators and keywords in the
given text (C program) file.
lex part
%{
#include <stdio.h>
#include "y.tab.h"
extern yylval;
%}
%%
[ t] ;
[+|-|*|/|=|<|>] {printf("operator is %sn",yytext);return OP;}
[0-9]+ {yylval = atoi(yytext); printf("numbers is %dn",yylval); return DIGIT;}
int|char|bool|float|void|for|do|while|if|else|return|void {printf("keyword is%sn",yytext);return
KEY;}
[a-zA-Z0-9]+ {printf("identifier is %sn",yytext);return ID;}
. ;
%%
yacc part
%{
#include <stdio.h>
#include <stdlib.h>
int id=0, dig=0, key=0, op=0;
%}
%token DIGIT ID KEY OP
%%
input:
DIGIT input {dig++;}
| ID input {id++;}
| KEY input { key++; }
| OP input {op++;}
| DIGIT { dig++;}
| ID { id++;}
| KEY {key++;}
| OP {op++;}
;
%%
#include <stdio.h>
extern int yylex();
extern int yyparse();
extern FILE *yyin;
main()
{
FILE *myfile = fopen("input.c", "r");
if (!myfile)
{
printf("I can't open input.c!");
39. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 39
return -1;
}
yyin = myfile;
do
{
yyparse();
}
while (!feof(yyin));
printf("Number of numbers = %dn Number ofKeywords = %dn Number of Identifiers =
%dn Number of noperators = %dn",dig, key,id, op);
}
int yyerror()
{
printf("error");
exit(0);
}
Ouput: vim input.c
void main()
{
int a;
float b;
char c;
char d;
int sum=40;
if(sum>=40)
printf("---pass--");
else
printf("---fail--");
}
CRC@CRC:~/Desktop/finss$ yacc -d 7.y
CRC@CRC:~/Desktop/finss$ lex 7.l
CRC@CRC:~/Desktop/finss$ gcc lex.yy.c y.tab.c -ll –ly
CRC@CRC:~/Desktop/finss$ ./a.out
keyword is void
identifier is main
keyword is int
identifier is a
keyword is float
identifier is b
keyword is char
identifier is c
keyword is char
40. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 40
identifier is d
keyword is int
identifier is sum
operator is =
numbers is 40
keyword is if
identifier is sum
operator is >
operator is =
numbers is 40
identifier is printf
identifier is pass
keyword is else
identifier is printf
identifier is fail
Number of numbers = 2
Number of Keywords = 8
Number of Identifiers = 11
Number of n operators = 3
ubuntu16@ubuntu:~/Desktop/finss$ vim crc.c
#include<stdio.h>
void main()
{
int a=75;
float f=99.99;
if(f>a)
printf("distinction");
else
printf("First class");
}
CRC16@CRC:~/Desktop/finss$ yacc -d 7.y
CRC16@CRC:~/Desktop/finss$ lex 7.l
CRC16@CRC:~/Desktop/finss$ gcc lex.yy.c y.tab.c -ll -ly
CRC16@CRC:~/Desktop/finss$ ./a.out
identifier is include
operator is <
identifier is stdio
identifier is h
operator is >
41. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 41
keyword is void
identifier is main
keyword is int
identifier is a56
keyword is float
identifier is f
keyword is char
identifier is c
keyword is char
identifier is m
keyword is if
identifier is marks
operator is =
operator is =
numbers is 97
identifier is printf
identifier is distinction
keyword is else
identifier is printf
identifier is First
identifier is class
numbers = 1
Keywords = 7
Identifiers = 14
operators = 4
CRC16@CRC:~/Desktop/finss$ vim crc.c
CRC16@CRC:~/Desktop/finss$ yacc -d 7.y
CRC16@CRC:~/Desktop/finss$ lex 7.l
CRC16@CRC:~/Desktop/finss$ gcc lex.yy.c y.tab.c -ll -ly
CRC16@CRC:~/Desktop/finss$ ./a.out
identifier is include
operator is <
identifier is stdio
identifier is h
operator is >
keyword is void
identifier is main
keyword is int
identifier is a56
42. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 42
keyword is int
identifier is cm
keyword is float
identifier is f
keyword is char
identifier is c
keyword is char
identifier is m
keyword is if
identifier is marks
operator is =
operator is =
numbers is 97
identifier is printf
identifier is distinction
keyword is else
identifier is printf
identifier is First
identifier is class
numbers = 1
Keywords = 8
Identifiers = 15
operators = 4
CRC16@CRC:~/Desktop/finss$ vim crc.c
#include<stdio.h>
void main()
{
int a56;
int cm;
float f;
char c;
char m;
if(marks==97)
printf("distinction");
else
printf("First class");
}
43. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 43
7. Design, develop and implement a C/C++/Java program to simulate the working of
Shortest remaining time and Round Robin (RR) scheduling algorithms. Experiment
with different quantum sizes for RR algorithm.
a) SRT
import java.io.*;
public class SRT
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.println("Please enter the number of Processes: ");
n = Integer.parseInt(br.readLine());
int proc[][] = new int[n + 1][4];
//proc[][0] is the AT array,[][1] - RT,[][2] - WT,[][3] - TT
for(int i = 1; i <= n; i++)
{
System.out.println("Please enter the Arrival Time for Process " + i + ": ");
proc[i][0] = Integer.parseInt(br.readLine());
System.out.println("Please enter the Burst Time for Process " + i + ": ");
proc[i][1] = Integer.parseInt(br.readLine());
}
System.out.println();
//Calculation of Total Time and Initialization of Time Chart array
int total_time = 0;
for(int i = 1; i <= n; i++)
{
total_time += proc[i][1];
}
int time_chart[] = new int[total_time];
for(int i = 0; i < total_time; i++)
{
//Selection of shortest process which has arrived
int sel_proc = 0;
44. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 44
int min = 99999;
for(int j = 1; j <= n; j++)
{
if(proc[j][0] <= i)
//Condition to check if Process has arrived
{
if(proc[j][1] < min && proc[j][1] != 0)
{
min = proc[j][1];
sel_proc = j;
}
}
}
//Assign selected process to current time in the Chart
time_chart[i] = sel_proc;
//Decrement Remaining Time of selected process by 1 since it has been assigned the
//CPU for 1 unit of time
proc[sel_proc][1]--; //WT and TT Calculation
for(int j = 1; j <= n; j++)
{
if(proc[j][0] <= i)
{
if(proc[j][1] != 0)
{
proc[j][3]++;
//If process has arrived and it has not already completed execution its TT is //incremented by
1
if(j != sel_proc)
//If the process has not been currently assigned the CPU and has arrived its WT is
//incremented by 1
proc[j][2]++;
}
else if(j == sel_proc)
45. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 45
//This is a special case in which the process has been assigned CPU and has completed its
execution
proc[j][3]++;
}
}
//Printing the Time Chart
if(i != 0)
{
if(sel_proc != time_chart[i - 1])
//If the CPU has been assigned to a different Process we need to print the current
//value of time and the name of the new Process
{
System.out.print("--" + i + "--P" + sel_proc);
}
}
else
//If the current time is 0 i.e the printing has just started we need to print the name of the First
selected Process
System.out.print(i + "--P" + sel_proc);
if(i == total_time - 1)
//All the process names have been printed now we have to print the time at which execution
ends
System.out.print("--" + (i + 1));
}
System.out.println();
System.out.println();
//Printing the WT and TT for each Process
System.out.println("Pt WT t TT ");
for(int i = 1; i <= n; i++)
{
System.out.printf("%dt%2dmst%2dms",i,proc[i][2],proc[i][3]);
System.out.println();
}
46. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 46
System.out.println();
//Printing the average WT & TT
float WT = 0,TT = 0;
for(int i = 1; i <= n; i++)
{
WT += proc[i][2];
TT += proc[i][3];
}
WT /= n;
TT /= n;
System.out.println("The Average WT is: " + WT + "ms");
System.out.println("The Average TT is: " + TT + "ms");
}
}
Output: C:UsersChethanDesktop>javac SRT.java
C:UsersChethanDesktop>java SRT
Please enter the number of Processes:
4
Please enter the Arrival Time for Process 1:
0
Please enter the Burst Time for Process 1:
8
Please enter the Arrival Time for Process 2:
1
Please enter the Burst Time for Process 2:
4
Please enter the Arrival Time for Process 3:
2
Please enter the Burst Time for Process 3:
9
Please enter the Arrival Time for Process 4:
3
Please enter the Burst Time for Process 4:
47. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 47
5
0--P1--1--P2--5--P4--10--P1--17--P3--26
P WT TT
1 9ms 17ms
2 0ms 4ms
3 15ms 24ms
4 2ms 7ms
The Average WT is: 6.5ms
The Average TT is: 13.0ms
C:UsersChethanDesktop>java SRT
Please enter the number of Processes:
3
Please enter the Arrival Time for Process 1:
0
Please enter the Burst Time for Process 1:
10
Please enter the Arrival Time for Process 2:
1
Please enter the Burst Time for Process 2:
5
Please enter the Arrival Time for Process 3:
2
Please enter the Burst Time for Process 3:
5
0--P1--1--P2--6--P3--11--P1--20
P WT TT
1 10ms 20ms
2 0ms 5ms
3 4ms 9ms
The Average WT is: 4.6666665ms
The Average TT is: 11.333333ms
48. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 48
Output:
C:UsersChethanDesktop>java SRT
Please enter the number of Processes:
3
Please enter the Arrival Time for Process 1:
0
Please enter the Burst Time for Process 1:
5
Please enter the Arrival Time for Process 2:
2
Please enter the Burst Time for Process 2:
4
Please enter the Arrival Time for Process 3:
1
Please enter the Burst Time for Process 3:
7
0--P1--5--P2--9--P3--16
P WT TT
1 0ms 5ms
2 3ms 7ms
3 8ms 15ms
The Average WT is: 3.6666667ms
The Average TT is: 9.0ms
b) RR
import java.io.*;
class round
{
public static void main(String args[])throws IOException
{
DataInputStream in=new DataInputStream(System.in);
int i,j,k,q,sum=0;
System.out.println("Enter number of process:");
int n=Integer.parseInt(in.readLine());
49. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 49
int bt[]=new int[n];
int wt[]=new int[n];
int tat[]=new int[n];
int a[]=new int[n];
System.out.println("Enter brust Time:");
for(i=0;i<n;i++)
{
System.out.println("Enter brust Time for "+(i+1));
bt[i]=Integer.parseInt(in.readLine());
}
System.out.println("Enter Time quantum:");
q=Integer.parseInt(in.readLine());
for(i=0;i<n;i++)
a[i]=bt[i];
for(i=0;i<n;i++)
wt[i]=0;
do
{
for(i=0;i<n;i++)
{
if(bt[i]>q)
{
bt[i]-=q;
for(j=0;j<n;j++)
{
if((j!=i)&&(bt[j]!=0))
wt[j]+=q;
}
}
else
{
for(j=0;j<n;j++)
{
50. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 50
if((j!=i)&&(bt[j]!=0))
wt[j]+=bt[i];
}
bt[i]=0;
}
}
sum=0;
for(k=0;k<n;k++)
sum=sum+bt[k];
}
while(sum!=0);
for(i=0;i<n;i++)
tat[i]=wt[i]+a[i];
System.out.println("processttBTtWTtTAT");
for(i=0;i<n;i++)
{
System.out.println("process"+(i+1)+"t"+a[i]+"t"+wt[i]+"t"+tat[i]);
}
float avg_wt=0;
float avg_tat=0;
for(j=0;j<n;j++)
{
avg_wt+=wt[j];
}
for(j=0;j<n;j++)
{
avg_tat+=tat[j];
}
System.out.println("average waiting time "+(avg_wt/n)+"n Average turn around
time"+(avg_tat/n));
}
}
Output 1: C:UsersChethanDesktop>javac round.java
51. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 51
C:UsersChethanDesktop>java round
Enter number of process:
3
Enter brust Time:
Enter brust Time for 1
3
Enter brust Time for 2
4
Enter brust Time for 3
3
Enter Time quantum:
1
process BT WT TAT
process1 3 4 7
process2 4 6 10
process3 3 6 9
average waiting time 5.3333335
Average turn around time8.666667
Output 2: C:UsersChethanDesktop>java round
Enter number of process:
4
Enter brust Time:
Enter brust Time for 1
10
Enter brust Time for 2
4
Enter brust Time for 3
5
Enter brust Time for 4
3
Enter Time quantum:
3
process BT WT TAT
52. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 52
process1 10 12 22
process2 4 12 16
process3 5 13 18
process4 3 9 12
average waiting time 11.5
Average turn around time17.0
C:UsersChethanDesktop>
Completion Time: Time at which process completes its execution.
Turn Around Time: Time Difference between completion time and arrival time. Turn
Around Time = Completion Time – Arrival Time
Waiting Time(W.T): Time Difference between turn around time and burst time.
Waiting Time = Turn Around Time – Burst Time
8. Design, develop and implement a C/C++/Java program to implement Banker’s
algorithm. Assume suitable input required to demonstrate the results.
import java.util.Scanner;
public class Bankers
{
private int need[][],allocate[][],max[][],avail[][],np,nr;
private void input()
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter no. of processes and resources : ");
np=sc.nextInt(); //no. of process
nr=sc.nextInt(); //no. of resources
need=new int[np][nr]; //initializing arrays
max=new int[np][nr];
allocate=new int[np][nr];
avail=new int[1][nr];
System.out.println("Enter allocation matrix -->");
for(int i=0;i<np;i++)
for(int j=0;j<nr;j++)
allocate[i][j]=sc.nextInt(); //allocation matrix
System.out.println("Enter max matrix -->");
for(int i=0;i<np;i++)
for(int j=0;j<nr;j++)
max[i][j]=sc.nextInt(); //max matrix
System.out.println("Enter available matrix -->");
for(int j=0;j<nr;j++)
avail[0][j]=sc.nextInt(); //available matrix
53. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 53
sc.close();
}
private int[][] calc_need()
{
for(int i=0;i<np;i++)
for(int j=0;j<nr;j++) //calculating need matrix
need[i][j]=max[i][j]-allocate[i][j];
return need;
}
private boolean check(int i)
{
//checking if all resources for ith process can be allocated
for(int j=0;j<nr;j++)
if(avail[0][j]<need[i][j])
return false;
return true;
}
public void isSafe()
{
input();
calc_need();
boolean done[]=new boolean[np];
int j=0;
while(j<np){ //until all process allocated
boolean allocated=false;
for(int i=0;i<np;i++)
if(!done[i] && check(i)){ //trying to allocate
for(int k=0;k<nr;k++)
avail[0][k]=avail[0][k]-need[i][k]+max[i][k];
System.out.println("Allocated process : "+i);
allocated=done[i]=true;
j++;
}
if(!allocated) break; //if no allocation
}
if(j==np) //if all processes are allocated
System.out.println("nSafely allocated");
else
System.out.println("All proceess cant be allocated safely");
}
public static void main(String[] args)
{
new Bankers().isSafe();
}
54. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 54
}
Output:
Output: C:UsersChethanDesktop>javac Bankers.java
C:UsersChethanDesktop>java Bankers
Enter no. of processes and resources : 5
3
Enter allocation matrix -->
0
1
0
2
0
0
3
0
2
2
1
1
0
0
2
Enter max matrix -->
7
5
3
3
2
55. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 55
2
9
0
2
2
2
2
4
3
3
Enter available matrix -->
3
3
2
Allocated process : 1
Allocated process : 3
Allocated process : 4
Allocated process : 0
Allocated process : 2
Safely allocated
Output: C:UsersChethanDesktop> javac Bankers.java
C:UsersChethanDesktop22>java Bankers
Enter no. of processes and resources : 3
3
Enter allocation matrix -->
1
2
1
2
0
1
2
2
1
Enter max matrix -->
1
0
3
0
1
2
1
2
0
Enter available matrix -->
0
56. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 56
1
2
Allocated process : 0
Allocated process : 1
Allocated process : 2
Safely allocated
Output: C:UsersChethanDesktop22>javac Bankers.java
C:UsersChethanDesktop22>java Bankers
Enter no. of processes and resources : 3
4
Enter allocation matrix -->
1 2 2 1
1 0 3 3
1 2 1 0
Enter max matrix -->
3 3 2 2
1 1 3 4
1 3 5 0
Enter available matrix -->
3
1
1
2
Allocated process : 0
Allocated process : 1
Allocated process : 2
Safely allocated
9. Design, develop and implement a C/C++/Java program to implement page
replacement algorithms LRU and FIFO. Assume suitable input required to
demonstrate the results.
a)Least Recently Used(LRU):
import java.io.*;
public class lru
{
public static void main(String[] args) throws Exception
{
int f, p, num=0, pageHit=0, count=0, ptPage=0, pg=0;
int pages[];
57. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 57
int frame[];
int recent[];
boolean flag = true;
boolean flag2 = true;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));//STEP 1
System.out.println("Enter number of frames : ");
f = Integer.parseInt(br.readLine());
System.out.println("Enter number of pages : ");
p = Integer.parseInt(br.readLine());
frame = new int[f];
pages = new int[p];
recent = new int[f];
for(int i=0; i<f; i++) //STEP 2
{
frame[i] = -1;
recent[i] = -1;
}
System.out.println("Enter page number : ");
for(int i=0;i<p;i++)
pages[i] = Integer.parseInt(br.readLine());
for(int i=0; i<p; i++)
{
flag = true;
int page = pages[i];
for(int j=0; j<f; j++)
recent[j] = -1;
for(int j=0; j<f; j++) //check for page hit STEP 3
{
if(frame[j] == page)
62. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 62
frame : 5 2 6
frame : 5 2 6
frame : 5 3 6
frame : 1 3 6
frame : 1 3 6
frame : 1 3 6
frame : 1 3 6
frame : 1 2 6
frame : 1 2 4
frame : 3 2 4
No. of page hit : 9
Output 3) C:UsersChethanDesktop>
C:UsersChethanDesktop>java lru
Enter number of frames :
3
Enter number of pages :
10
Enter page number :
4
7
6
1
7
6
1
2
7
2
frame : 4 -1 -1
63. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 63
frame : 4 7 -1
frame : 4 7 6
frame : 1 7 6
frame : 1 7 6
frame : 1 7 6
frame : 1 7 6
frame : 1 2 6
frame : 1 2 7
frame : 1 2 7
No. of page hit : 4
b) FIFO
import java.io.*;
public class FIFO
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int frames, pointer = 0, hit = 0, fault = 0,ref_len;
int buffer[];
int reference[];
int mem_layout[][];
System.out.println("Please enter the number of Frames: ");
frames = Integer.parseInt(br.readLine());
System.out.println("Please enter the length of the Reference string: ");
ref_len = Integer.parseInt(br.readLine());
reference = new int[ref_len];
mem_layout = new int[ref_len][frames];
buffer = new int[frames];
for(int j = 0; j < frames; j++)
64. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 64
buffer[j] = -1;
System.out.println("Please enter the reference string: ");
for(int i = 0; i < ref_len; i++)
{
reference[i] = Integer.parseInt(br.readLine());
}
System.out.println();
for(int i = 0; i < ref_len; i++)
{
int search = -1;
for(int j = 0; j < frames; j++)
{
if(buffer[j] == reference[i])
{
search = j;
hit++;
break;
}
}
if(search == -1)
{
buffer[pointer] = reference[i];
fault++;
pointer++;
if(pointer == frames)
pointer = 0;
}
for(int j = 0; j < frames; j++)
mem_layout[i][j] = buffer[j];
65. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 65
}
for(int i = 0; i < frames; i++)
{
for(int j = 0; j < ref_len; j++)
System.out.printf("%3d ",mem_layout[j][i]);
System.out.println();
}
System.out.println("The number of Hits: " + hit);
System.out.println("Hit Ratio: " + (float)((float)hit/ref_len));
System.out.println("The number of Faults: " + fault);
}
}
Output: C:UsersChethanDesktop>java FIFO
Please enter the number of Frames:
3
Please enter the length of the Reference string:
6
Please enter the reference string:
3
2
2
4
5
4
3 3 3 3 5 5
-1 2 2 2 2 2
-1 -1 -1 4 4 4
The number of Hits: 2
Hit Ratio: 0.33333334
66. System Software & Operating System Lab
Chethan Raj C, BE, M.Tech (Ph.D), Dept. of CSE Page 66
The number of Faults: 4
Output: C:UsersChethanDesktop>java FIFO
Please enter the number of Frames:
3
Please enter the length of the Reference string:
10
Please enter the reference string:
4
7
6
1
7
6
1
2
7
2
4 4 4 1 1 1 1 1 1 1
-1 7 7 7 7 7 7 2 2 2
-1 -1 6 6 6 6 6 6 7 7
The number of Hits: 4
Hit Ratio: 0.4
The number of Faults: 6
C:UsersChethanDesktop>
67. 1. Round Robin Algorithm
2. Paging Concepts
3. LRU
4. FIFO
5. Deadlock
6. Bankers algorithm
Non-Contiguous Memory Allocation-
Non-contiguous memory allocation is a memory allocation technique.
It allows to store parts of a single process in a non-contiguous fashion.
Thus, different parts of the same process can be stored at different places in the main memory.
Techniques-
There are two popular techniques used for non-contiguous memory allocation-
Paging-
1. Paging is a fixed size partitioning scheme.
2. In paging, secondary memory and main memory are divided into equal fixed size
partitions.
3. The partitions of secondary memory are called as pages.
4. The partitions of main memory are called as frames.
68. Each process is divided into parts where size of each part is same as page size.
The size of the last part may be less than the page size.
The pages of process are stored in the frames of main memory depending upon their
availability.
Consider a process is divided into 4 pages P0, P1, P2 and P3.
Depending upon the availability, these pages may be stored in the main memory frames in a non-
contiguous fashion as shown-
Translating Logical Address into Physical Address-
CPU always generates a logical address.
A physical address is needed to access the main memory.
Following steps are followed to translate logical address into physical address-
Step-01:
CPU generates a logical address consisting of two parts-
1. Page Number
69. 2. Page Offset
Page Number specifies the specific page of the process from which CPU wants to read the
data.
Page Offset specifies the specific word on the page that CPU wants to read.
Step-02:
For the page number generated by the CPU,
Page Table provides the corresponding frame number (base address of the frame) where that
page is stored in the main memory.
Step-03:
The frame number combined with the page offset forms the required physical address.
Frame number specifies the specific frame where the required page is stored.
Page Offset specifies the specific word that has to be read from that page.
Fig: Translating Logical address to physical address
Advantages-
The advantages of paging are-
1. It allows to store parts of a single process in a non-contiguous fashion.
2. It solves the problem of external fragmentation.
Disadvantages-
70. The disadvantages of paging are-
1. It suffers from internal fragmentation.
2. There is an overhead of maintaining a page table for each process.
3. The time taken to fetch the instruction increases since now two memory accesses are
required.
A page fault occurs when a page referenced by the CPU is not found in the main memory.
The required page has to be brought from the secondary memory into the main memory.
A page has to be replaced if all the frames of main memory are already occupied.
Page Replacement Algorithms in Operating Systems
1. Page replacement is a process of swapping out an existing page from the frame of a main
memory and replacing it with the required page.
2. All the frames of main memory are already occupied.
3. Thus, a page has to be replaced to create a room for the required page.
Page replacement algorithms help to decide which page must be swapped out from the main
memory to create a room for the incoming page.
Various page replacement algorithms are-
A good page replacement algorithm is one that minimizes the number of page faults.
In an operating system that uses paging for memory management, a page replacement algorithm
is needed to decide which page needs to be replaced when new page comes in.
Page Fault – A page fault happens when a running program accesses a memory page that is
mapped into the virtual address space, but not loaded in physical memory.
Since actual physical memory is much smaller than virtual memory, page faults happen. In case
of page fault, Operating System might have to replace one of the existing pages with the newly
needed page. Different page replacement algorithms suggest different ways to decide which page
to replace. The target for all algorithms is to reduce the number of page faults.
71. Page Replacement Algorithms : First In First Out (FIFO) –
FIFO Page Replacement Algorithm.
• As the name suggests, this algorithm works on the principle of ―First in First out―.
• It replaces the oldest page that has been present in the main memory for the longest time.
• It is implemented by keeping track of all the pages in a queue.
• 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 be replaced page in the front of the queue is selected for removal.
Ex:
Example: Consider page reference string 1, 3, 0, 3, 5, 6 with 3 page frames.Find number of
page faults.
72. Initially all slots are empty, so when 1, 3, 0 came they are allocated to the empty slots —> 3
Page Faults.
when 3 comes, it is already in memory so —> 0 Page Faults.
Then 5 comes, it is not available in memory so it replaces the oldest page slot i.e 1. —>1 Page
Fault.
6 comes, it is also not available in memory so it replaces the oldest page slot i.e 3 —>1 Page
Fault.
Finally when 3 come it is not avilable so it replaces 0 1 page fault
Least Recently Used –
• As the name suggests, this algorithm works on the principle of ―Least Recently Used―.
• It replaces the page that has not been referred by the CPU for the longest time.
In this algorithm page will be replaced which is least recently used.
EX:
Example: Consider the page reference string 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 with 4 page
frames. Find number of page faults.
73. Initially all slots are empty, so when 7 0 1 2 are allocated to the empty slots —> 4 Page faults
0 is already their so —> 0 Page fault.
when 3 came it will take the place of 7 because it is least recently used —>1 Page fault
0 is already in memory so —> 0 Page fault.
4 will takes place of 1 —> 1 Page Fault
Now for the further page reference string —> 0 Page fault because they are already available in
the memory.
Ex: Assume there are 3 frames, and consider the reference string given in example . Show the
content of memory after each memory reference if FIFO page replacement algorithm issued.
Find also the number of page faults.
10 page faults are caused by FIFO
Ex: A system uses 3 page frames for storing process pages in main memory. It uses the
First in First out (FIFO) page replacement policy. Assume that all the page frames are
initially empty. What is the total number of page faults that will occur while processing the
page reference string given below-
4 , 7, 6, 1, 7, 6, 1, 2, 7, 2
Also calculate the hit ratio and miss ratio.
Solution: Total number of references = 10
74. From here,
Total number of page faults occurred = 6
Calculating Hit ratio-
Total number of page hits
= Total number of references – Total number of page misses or page faults
= 10 – 6
= 4
Thus, Hit ratio
= Total number of page hits / Total number of references
= 4 / 10
= 0.4 or 40%
Calculating Miss ratio-
Total number of page misses or page faults = 6
Thus, Miss ratio
= Total number of page misses / Total number of references
= 6 / 10
= 0.6 or 60%
Alternatively,
75. Miss ratio
= 1 – Hit ratio
= 1 – 0.4
= 0.6 or 60%
Ex: Assume there are 3 frames, and consider the reference string given in example . Show
the content of memory after each memory reference if LRU page replacement algorithm is
used. Find also the number of page faults
This algorithm resulted in 9 page faults.
Ex: A system uses 3 page frames for storing process pages in main memory. It uses the
Least Recently Used (LRU) page replacement policy. Assume that all the page frames are
initially empty. What is the total number of page faults that will occur while processing the
page reference string given below-
4 , 7, 6, 1, 7, 6, 1, 2, 7, 2
Also calculate the hit ratio and miss ratio.
Solution-
Total number of references = 10
From here,
Total number of page faults occurred = 6
In the similar manner as above-
• Hit ratio = 0.4 or 40%
• Miss ratio = 0.6 or 60%
76. Ex: A system uses 3 page frames for storing process pages in main memory. It uses the
Optimal page replacement policy. Assume that all the page frames are initially empty.
What is the total number of page faults that will occur while processing the page reference
string given below-
4 , 7, 6, 1, 7, 6, 1, 2, 7, 2
Also calculate the hit ratio and miss ratio.
Solution-
Total number of references = 10
From here,
Total number of page faults occurred = 5
In the similar manner as above-
• Hit ratio = 0.5 or 50%
• Miss ratio = 0.5 or 50%
Ex: Consider the example on LRU that consists of three frames
The above example results in 9 page faults
Round robin scheduling algorithm
Round Robin Scheduling is the preemptive scheduling algorithm. We assign a fixed time to all
processes for execution, this time is called time quantum.
77. All processes can execute only until their time quantum and then leave the CPU and give a
chance to other processes to complete their execution according to time quantum.
In Round-robin scheduling, each ready task runs turn by turn only in a cyclic queue for a limited
time slice.
Round robin scheduling algorithm is used to schedule process fairly each job a time slot or
quantum and the interrupting the job if it is not completed by then the job come after the other
job which are arrived in the quantum time that make these scheduling fairly.
Context switching mechanisms store the states of preempted processes.
Time quantum = 2
Process Burst Time Arrival
P1 4 2nd
P2 2 3rd
P3 8 1st
P4 3 4th
Characteristics of Round-Robin Scheduling
Here are the important characteristics of Round-Robin Scheduling:
1. Round robin is a pre-emptive algorithm
2. Round robin is cyclic in nature so starvation doesn’t occur
3. Round robin is variant of first come, first served scheduling
4. The CPU is shifted to the next process after fixed interval time, which is called time
quantum/time slice.
5. The process that is preempted is added to the end of the queue.
78. 6. Round robin is a hybrid model which is clock-driven
7. Time slice should be minimum, which is assigned for a specific task that needs to be
processed. However, it may differ OS to OS.
8. It is a real time algorithm which responds to the event within a specific time limit.
9. Round robin is one of the oldest, fairest, and easiest algorithm.
10. Widely used scheduling method in traditional OS.
11. RR scheduling is also known as Time slicing scheduling
Advantage of Round-robin Scheduling
Here, are pros/benefits of Round-robin scheduling method:
1. It doesn't face the issues of starvation or convoy effect.
2. Finding a correct time quantum is a quite difficult task in this system.
3. Each process is served by CPU for a fixed time so priority is same for each one
4. Starvation does not occur because of its cyclic nature.
5. All the jobs get a fair allocation of CPU.
6. It deals with all process without any priority
7. If you know the total number of processes on the run queue, then you can also assume the
worst-case response time for the same process.
8. This scheduling method does not depend upon burst time. That's why it is easily
implementable on the system.
9. Once a process is executed for a specific set of the period, the process is preempted, and
another process executes for that given time period.
10. Allows OS to use the Context switching method to save states of preempted processes.
11. It gives the best performance in terms of average response time.
Disadvantages of Round-robin Scheduling
Here, are drawbacks/cons of using Round-robin scheduling:
1. If slicing time of OS is low, the processor output will be reduced.
2. This method spends more time on context switching
3. Its performance heavily depends on time quantum.
79. 4. Priorities cannot be set for the processes.
5. Round-robin scheduling doesn't give special priority to more important tasks.
6. Decreases comprehension
7. Lower time quantum results in higher the context switching overhead in the system.
8. Throughput depends on quantum time.
9. If we want to give some process priority, we cannot.
Output 1:
C:UsersChethanDesktop>javac round.java
C:UsersChethanDesktop>java round
Enter number of process:
3
Enter brust Time:
Enter brust Time for 1
3
Enter brust Time for 2
4
Enter brust Time for 3
3
Enter Time quantum:
1
process BT WT TAT
process1 3 4 7
process2 4 6 10
80. process3 3 6 9
average waiting time 5.3333335
Average turn around time8.666667
Output 2: C:UsersChethanDesktop>java round
Enter number of process:
4
Enter brust Time:
Enter brust Time for 1
10
Enter brust Time for 2
4
Enter brust Time for 3
5
Enter brust Time for 4
3
Enter Time quantum:
3
process BT WT TAT
process1 10 12 22
process2 4 12 16
process3 5 13 18
81. process4 3 9 12
average waiting time 11.5
Average turn around time17.0
C:UsersChethanDesktop>
Completion Time: Time at which process completes its execution.
Turn Around Time: Time Difference between completion time and arrival time. Turn
Around Time = Completion Time – Arrival Time
Waiting Time(W.T): Time Difference between turn around time and burst time.
Waiting Time = Turn Around Time – Burst Time
Bankers algorithm:
Banker’s Algorithm is a deadlock avoidance algorithm.
It maintains a set of data using which it decides whether to entertain the request of any process or
not.
It follows the safety algorithm to check whether the system is in a safe state or not
In a deadlock state, the execution of multiple processes is blocked.
Deadlock avoidance strategy involves maintaining a set of data.
The data is used to make a decision whether to entertain any new request or not.
If entertaining the new request causes the system to move in an unsafe state, then it is discarded.
Note: Available is 1D and other three is 2D data
82. Safe State
A system is said to be in safe state when all the processes can be executed in some arbitrary
sequence with the available number of resources.
Safety Algorithm is executed to check whether the resultant state after allocating the resources is
safe or not.
Work: It is a single dimensional array that specifies the number of instances of each resource
type currently available.
83. Ex: Work[R1] = K. It means K instances of resource type R1 are currently available.
Finish: It is a single dimensional array that specifies whether the process has finished its
execution or not.
Ex: Finish[P1] = 0. It means process P1 is still left to execute.
Characteristics of Banker's Algorithm
Here are important characteristics of banker's algorithm:
Keep many resources that satisfy the requirement of at least one client
Whenever a process gets all its resources, it needs to return them in a restricted period.
When a process requests a resource, it needs to wait
The system has a limited number of resources
Advance feature for max resource allocation
Disadvantage of Banker's algorithm
Here, are cons/drawbacks of using banker's algorithm
Does not allow the process to change its Maximum need while processing
It allows all requests to be granted in restricted time, but one year is a fixed period for
that.
All processes must know and state their maximum resource needs in advance.
Summary:
Banker's algorithm is used majorly in the banking system to avoid deadlock. It helps you
to identify whether a loan will be given or not.
Notations used in banker's algorithms are 1) Available 2) Max 3) Allocation 4) Need
Resource request algorithm enables you to represent the system behavior when a specific
process makes a resource request.
Banker's algorithm keeps many resources that satisfy the requirement of at least one
client
The biggest drawback of banker's algorithm this that it does not allow the process to
change its Maximum need while processing.
84. 1
Banker’s Algorithm Example Solutions
Exercise 1
Assume that there are 5 processes, P0 through P4, and 4 types of resources. At T0 we have the
following system state:
Max Instances of Resource Type A = 3 (2 allocated + 1 Available)
Max Instances of Resource Type B = 17 (12 allocated + 5 Available)
Max Instances of Resource Type C = 16 (14 allocated + 2 Available)
Max Instances of Resource Type D = 12 (12 allocated + 0 Available)
Given Matrices
Allocation Matrix
(N0 of the allocated resources By a
process)
Max Matrix
Max resources that may be used by
a process
Available Matrix
Not Allocated
Resources
A B C D A B C D A B C D
P0 0 1 1 0 0 2 1 0 1 5 2 0
P1 1 2 3 1 1 6 5 2
P2 1 3 6 5 2 3 6 6
P3 0 6 3 2 0 6 5 2
P4 0 0 1 4 0 6 5 6
Total 2 12 14 12
1. Create the need matrix (max-allocation)
Need Matrix = Max Matrix
– Allocation Matrix
A B C D
P0 0 1 0 0
P1 0 4 2 1
P2 1 0 0 1
P3 0 0 2 0
P4 0 6 4 2
2. Use the safety algorithm to test if the system is in a safe state or not?
a. We will first define work and finish:
Initially work = available = ( 1, 5 , 2, 0)
Finish = False for all processes
Finish matrix
P0 False
P1 False
P2 False
P3 False
P4 False
Work vector
1 5 2 0
b. Check the needs of each process [ needs(pi) <= Max(pi)], if this condition is true:
Execute the process , Change Finish[i] =True
Release the allocated Resources by this process
Change The Work Variable = Allocated (pi) + Work
Need(i) = Max(i) – Allocated(i)
(i=0) (0,2,1,0) - (0,1,1,0) = (0,1,0,0)
(i=1) (1,6,5,2) - (1,2,3,1) = (0,4,2,1)
(i=2) (2,3,6,6) - (1,3,6,5) = (1,0,0,1)
(i=3) (0,6,5,2) - (0,6,3,2) = (0,0,2,0)
(i=4) (0,6,5,6) - (0,0,1,4) = (0,6,4,2)
Ex. Process P1 has max of (1,6,5,2) and allocated by (1,2,3,1)
Need(p1) = max(p1)- allocated(p1) = (1,6,5,2) – ( 1,2,3,1) = (0,4,2,1)
85. 2
need0 (0,1,0,0) <= work(1,5,2,0)
P0 will be
executed because
need(P0) <= Work
P0 will be True
Finish matrix
P0 – 1 True
P1 False
P2 False
P3 False
P4 False
P0 will release the allocated
resources(0,1,1,0)
Work = Work
(1,5,2,0)+Allocated(P0)
(0,1,1,0) = 1,6,3,0
Work vector
1 6 3 0
Need1 (0,4,2,1) <= work(1,6,3,0) Condition Is False P1 will Not be executed
Need2 (1,0,0,1) <= work(1,6,3,0) Condition Is False P2 will Not be executed
Need3 (0,0,2,0) <= work(1,6,3,0) P3 will be executed
P3 will be
executed because
need(P3) <= Work
P3 will be True
Finish matrix
P0 – 1 True
P1 False
P2 False
P3 -2 True
P4 False
P3 will release the allocated
resources (0,6,3,2)
Work = Work
(1,6,3,0)+Allocated(P3)
( 0,6,3,2) = 1,12,6,2
Work vector
1 12 6 2
Need4 (0,6,4,2) <= work(1,12,6,2) P4 will be executed
P4 will be
executed because
need(P4) <= Work
P4 will be True
Finish matrix
P0 – 1 True
P1 False
P2 False
P3 -2 True
P4 -3 True
P4 will release the allocated
resources (0,0,1,4)
Work = Work
(1,12,6,2) + Allocated(P4)
(0,0,1,4) = 1,12,7,6
Work vector
1 12 7 6
Need1 (0,4,2,1) <= work(1,12,7,6) P1 will be executed
P1 will be
executed because
need(P1) <= Work
P1 will be True
Finish matrix
P0 – 1 True
P1 -4 True
P2 False
P3 -2 True
P4 -3 True
P1 will release the allocated
resources (1,2,3,1)
Work = Work
(1,12,7,6) + Allocated(P1)
(1,2,3,1) = 2,14,10,7
Work vector
2 14 10 7
Need2 (1,0,0,1) <= work(2,14,10,7) P2 will be executed
P2 will be
executed because
need(P2) <= Work
P2 will be True
Finish matrix
P0 – 1 True
P1 -4 True
P2 -5 True
P3 -2 True
P4 -3 True
P2 will release the allocated
resources (1,3,6,5)
Work = Work
(2,14,10,7) + Allocated(P1)
(1,3,6,5) = 3,17,16,12
Work vector
3 17 16 12
The system is in a safe state and the processes will be executed in the following order:
P0,P3,P4,P1,P2
86. 3
Exercise 2:
If the system is in a safe state, can the following requests be granted, why or why not? Please
also run the safety algorithm on each request as necessary.
a. P1 requests (2,1,1,0)
We cannot grant this request, because we do not have enough available
instances of resource A.
b. P1 requests (0,2,1,0)
There are enough available instances of the requested resources, so first let’s
pretend to accommodate the request and see the system looks like:
Allocation Max Available
A B C D A B C D A B C D
P0 0 1 1 0 0 2 1 0 1 3 1 0
P1 1 4 4 1 1 6 5 2
P2 1 3 6 5 2 3 6 6
P3 0 6 3 2 0 6 5 2
P4 0 0 1 4 0 6 5 6
Need Matrix
A B C D
P0 0 1 0 0
P1 0 2 1 1
P2 1 0 0 1
P3 0 0 2 0
P4 0 6 4 2
Now we need to run the safety algorithm:
Initially
Work vector Finish matrix
1 P0 False
3 P1 False
1 P2 False
0 P3 False
P4 False
Let’s first look at P0. Need0 (0,1,0,0) is less than
work, so we change the work vector and finish
matrix as follows:
Work vector Finish matrix
1 P0 True
4 P1 False
2 P2 False
0 P3 False
P4 False
Need1 (0,2,1,1) is not less than work, so we need to move on to P2.
Need2 (1,0,0,1) is not less than work, so we need to move on to P3.
Need3 (0,0,2,0) is less than or equal to work.
Let’s update work and finish:
Work vector Finish matrix
1 P0 True
10 P1 False
5 P2 False
2 P3 True
P4 False
Let’s take a look at Need4 (0,6,4,2). This is
less than work, so we can update work and
finish:
Work vector Finish matrix
1 P0 True
10 P1 False
6 P2 False
6 P3 True
P4 True
87. 4
We can now go back to P1. Need1 (0,2,1,1) is less than work, so work and finish can be updated:
Work vector Finish matrix
1 P0 True
14 P1 True
10 P2 False
7 P3 True
P4 True
Finally, Need2 (1,0,0,1) is less than work, so we can also accommodate this. Thus, the system is
in a safe state when the processes are run in the following order:
P0,P3,P4,P1,P2. We therefore can grant the resource request.
88. 5
Exercise 3
Assume that there are three resources, A, B, and C. There are 4 processes P0 to P3. At T0
we have the following snapshot of the system:
Allocation Max Available
A B C A B C A B C
P0 1 0 1 2 1 1 2 1 1
P1 2 1 2 5 4 4
P2 3 0 0 3 1 1
P3 1 0 1 1 1 1
1.Create the need matrix.
Need
A B C
P0 1 1 0
P1 3 3 2
P2 0 1 1
P3 0 1 0
2. Is the system in a safe state? Why or why not?
In order to check this, we should run the safety algorithm. Let’s create the work vector
and finish matrix:
Work vector Finish
matrix
2 P0 False
1 P1 False
1 P2 False
P3 False
Need0 (1,1,0) is less than work, so let’s go
ahead and update work and finish:
Work vector Finish
matrix
3 P0 True
1 P1 False
2 P2 False
P3 False
Need1 (3,3,2) is not less than work, so we have to move on to P2.
Need2 (0,1,1) is less than work, let’s
update work and finish:
Work vector Finish matrix
6 P0 True
1 P1 False
2 P2 True
P3 False
Need3 (0,1,0) is less than work, we
can update work and finish:
Work vector Finish matrix
7 P0 True
1 P1 False
3 P2 True
P3 True
We now need to go back to P1. Need1 (3,3,2) is not less than work, so we cannot continue.
Thus, the system is not in a safe state.