18csl66 - Ss Lab Manual
18csl66 - Ss Lab Manual
18csl66 - Ss Lab Manual
LABORATORY MANUAL
SEMESTER: VI
Vision
Mission
"BIET contributes to the growth and development of its students by imparting a broad based
engineering education and empowering them to be successful in their chosen field by inculcating in
them positive approach, leadership qualities and ethical values"
M1 Adapting best teaching and learning techniques that cultivates Questioning and Reasoning
culture among the students.
M2 Creating collaborative learning environment that ignites the critical thinking in students and
leading to the innovation.
M3 Establishing Industry Institute relationship to bridge the skill gap and make them industry
ready and relevant.
M4 Mentoring students to be socially responsible by inculcating ethical and moral values.
PO2. Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
PO6. The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice
PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.
1. PSO1: Analyze and develop solutions for problems that are complex in nature but
applying the knowledge acquired from the core subjects of this program..
2. PSO2: To develop secure, Scalable, Resilient and distributed applications for
industry and societal requirements.
3. PSO3: To learn and apply the concepts and construct of emerging technologies like
Artificial Intelligence, Machine learning, Deep learning, Big Data Analytics, IOT,
Cloud Computing, etc for any real time problems.
PEO1: To apply skills acquired in the discipline of Computer Science and Engineering for
solving societal and industrial problems with apt technology intervention
PEO2:
To continue their career in industry/academia or to pursue higher studies and research.
PEO3: To become successful entrepreneurs, innovators to design and develop software
products and services that meet the societal, technical and business challenges.
PEO4: To work in the diversified environment by acquiring leadership qualities with
effective communication skills accompanied by professional and ethical values.
SYSTEM SOFTWARE LABORATORY
[As per Choice Based Credit System (CBCS)scheme]
(Effective from the academic year 2018 -2019)
SEMESTER – VI
Subject Code 18CSL66 CIE Marks 40
Number of Contact Hours/Week 0:2:2 SEE Marks 60
Total Number of Lab Contact Hours 36 Exam Hours 03 Hrs
CREDITS – 02
Course objectives: This course will enable 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
Description (If any):
Exercises to be prepared with minimum three files (Where ever necessary):
1. Header file.
2. Implementation file.
3. 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.
Lab Experiments:
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 | . Use this table to
parse the sentence: abba$
T1 = -B
T2 = C + D 40
T3 = T1 + T2
A = T3
11. Program 6 :
a) Write a LEX program to eliminate comment lines in a C 43
CHAPTER1
Introduction to LEX
Lex and YACC helps you write programs that transforms structured input. Lex generates C code
for lexical analyzer where as YACC generates Code for Syntax analyzer. Lexical analyzer is build
using a tool called LEX. Input is given to LEX and lexical analyzer is generated.
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.
Definition
Section
Rule Section
Lex specification is translated into a
Code Section file containing a C routine called Lex.yy.c code
yylex()
%% is a delimiter to the mark the beginning of the Rule section. The second %% is optional, but
the first is required to mark the beginning of the rules. The definitions and the
code/subroutines are often omitted
Programming in Lex:
Programming in Lex can be divided into three steps:
Page 1
System Software Laboratory 18CSL66
Note: If the scanner is part of a parser developed using Yacc, only steps 1 and 2 should be
performed. Read the part B on Yacc.
Now let's look at the kind of program format that Lex understands. A Lex program is divided into
three sections:
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 %%.
Let us consider a word counting lex program to understand the sections in detail.
In this section we can add C variable declarations. We will declare an integer variable here for
our word-counting program that holds the number of words counted by the program.
int wordCount = 0;
%}
chars [A-za-z\_\'\.\"]
numbers ([0-9])+
%%
The double percent sign implies the end of this section and the beginning of the second of
the three sections in Lex programming.
Let's look at the Lex rules for describing the token that we want to match. (We'll use C to define
what to do when a token is matched.) Continuing with our word-counting program, here are the
rules for matching tokens.
{whitespace} { /* do nothing*/ }
%%
Page 2
System Software Laboratory 18CSL66
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*/
return 1;
In the preceding sections we've discussed the basic elements of Lex programming,which should
help you in writing simple lexical analysis programs
This produces the lex.yy.c file, which can be compiled using a C compiler. It can also be
used with a parser to produce an executable, or you can include the Lex library in the link
step with the option –ll.
Page 3
System Software Laboratory 18CSL66
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 of parsing.
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
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
[] 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
? Matches zero or one occurrences of the preceding pattern.
Ex: -?[0-9]+ matches a signed number including an optional leading
$ Matches end of line as the last character of the pattern.
{} 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:
\ 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.
Page 4
System Software Laboratory 18CSL66
^ Negation.
Regular Meaning
expression
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
[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
Page 5
System Software Laboratory 18CSL66
CHAPTER 2
Introduction to YACC
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.
Steps
in writing YACC Program:
Page 6
System Software Laboratory 18CSL66
When we run YACC, it generates a parser in file y.tab.c and also creates an include file y.tab.h. To
obtain tokens, YACC calls yylex. Function yylex has a return type of int and returns the token.
Values associated with the token are returned by lex in variable yylval.
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
%%
RULE SECTION
%%
CODE SECTION
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
%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
Page 7
System Software Laboratory 18CSL66
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.
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.
Page 8
System Software Laboratory 18CSL66
CHAPTER 3
Introduction to UNIX
Basic UNIX commands
Folder/Directory Commands and Options
Page 9
System Software Laboratory 18CSL66
File Utilities
Page 10
System Software Laboratory 18CSL66
CHAPTER 4
Introduction to Operating System
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 beingexecuted
Waiting : The process is waiting for some event to occur
Ready : The process is waiting to be assigned to a process
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 functions parameters, return
addresses and local variables
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
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 readyqueue.
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.
Page 11
System Software Laboratory 18CSL66
The different scheduling algorithms are
First Come First Serve, is just like FIFO (First in First out) Queue data structure, where the
data element which is added to the queue first, is the one who leaves the queue first.
This is used in Batch Systems.
It's easy to understand and implement programmatically, using a Queue data structure,
where a new process enters through the tail of the queue, and the scheduler selectsprocess
from the head of the queue.
A perfect real life example of FCFS scheduling is buying tickets at ticket counter.
LRU page replacement policy is based on the observation that pages that have been heavily used
in the last few instructions will probably be heavily used again in the next few. Conversely, pages
that have not been used for ages will probably remain unused for a long time.
Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process
with the smallest execution time to execute next. SJN is a non-preemptive algorithm.
Shortest Job first has the advantage of having a minimum average waiting time among all
scheduling algorithms.
It may cause starvation if shorter processes keep coming. This problem can be solved using
the concept of aging.
Page 12
System Software Laboratory 18CSL66
It is practically infeasible as Operating System may not know burst time and therefore may
not sort them. While it is not possible to predict execution time, several methods can be
used to estimate the execution time for a job, such as a weighted average of previous
execution times. SJF can be used in specialized environments where accurate estimates of
running time are available
Page 13
System Software Laboratory 18CSL66
Banker’s Algorithm in Operating System
Banker’s Algorithm is a resource allocation and deadlock avoidance algorithm. This algorithm
test for safety simulating the allocation for predetermined maximum possible amounts of all
resources, then makes an “s-state” check to test for possible activities, before decidingwhether
allocation should be allowed to continue.
In simple terms, it checks if allocation of any resource will lead to deadlock or not, OR is it safe
to allocate a resource to a process and if not then resource is not allocated to that process.
Determining a safe sequence (even if there is only 1) will assure that system will not go into
deadlock.
Banker’s algorithm is generally used to find if a safe sequence exists or not. But here we will
determine the total number of safe sequences and print all safe sequences.
Page 14
System Software Laboratory 18CSL66
CHAPTER 5
Sample Lex and Yacc Programs
Examples of sample Lex Program and Yacc Programs
Sample Program 1
%{
#include<stdio.h>
int cc=0,nn=0;
%}
%option noyywrap
%%
[a-zA-Z] cc++;
[0-9] nn++;
%%
main()
{
yylex();
printf("num of characters %d\nnum of numbers %d\n",cc,nn);
Output
student@student:~/naveen$ lex countnumbersletter.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
amith kumar
9912367987
ajay kumar
9531256834
num of characters 19
num of numbers 20
student@student:~/naveen$
Sample Program 2
%{
#include<stdio.h>
int wc=0;
%}
%option noyywrap
%%
[^ \t\n]+ wc++;
%%
Page 15
System Software Laboratory 18CSL66
main()
{
yylex();
printf("num of words %d\n",wc);
}
Output
student@student:~/naveen$ lex sample.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
BIET Colllege of Engineering
num of words 4
Sample Program 3
%{
#include<stdio.h>
int vc=0,cc=0;
%}
%option noyywrap
%%
[aeiouAEIOU] vc++;
[a-zA-Z] cc++;
%%
main()
{
printf("enter input\n");
yylex();
printf("num of vowels %d\n no of consonants %d\n",vc,cc);
}
Output
student@student:~/naveen$ lex vowelscount.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter input
BIET College of Engineering
num of vowels 11
no of consonants 13
student@student:~/naveen$
Sample Program 4
%{
#include<stdio.h>
int countcomment=0;
%}
Page 16
System Software Laboratory 18CSL66
%option noyywrap
%%
"/*"[^"*/"]*"*/" countcomment++;
"//".* countcomment++;
%%
main()
{
printf("enter comment lines\n");
yylex();
printf("No of Comments %d\n",countcomment);
}
Output
student@student:~/naveen$ lex countcomments.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter comment lines
// BIET College of Engineering
/* */
// this is ss os lab
/* Welcome* /
No of Comments 4
student@student:~/naveen$
Sample Program 5
Aim: Program to count the number of characters, words, spaces and lines in a given input
file.
%{
#include<stdio.h>
int wc,cc,lc,sc;
%}
word[^ \t\n]+
line[\n]
space[ ]
%%
{word} {wc++;cc+=yyleng;}
{line} {lc++;cc++;}
{space} {sc++;cc++;}
%%
int main(int argc,char * argv[])
{
if(argc!=2)
{
Page 17
System Software Laboratory 18CSL66
printf("\n\t Usage:./a.out filename\n");
return 0;
}
yyin=fopen(argv[1],"r");
yylex();
printf("\n Number of lines=%d",lc);
printf("\n Number of words=%d",wc);
printf("\n Number of character=%d",cc);
printf("\n Number of spaces=%d\n",sc);
return 0;
}
Output1
student@student:~/naveen$ lex countlswc.l
student@student:~/naveen$ cc lex.yy.c -ll
student@student:~/naveen$ cat a.txt
BIET college of engineering
student@student:~/naveen$ ./a.out a.txt
Number of lines=1
Number of words=4
Number of character=28
Number of spaces=3
student@student:~/naveen$
Output2
student@student:~/naveen$ lex countlswc.l
student@student:~/naveen$ cc lex.yy.c -ll
student@student:~/naveen$ cat b.txt
BIET college of
engineering
student@student:~/naveen$ ./a.out b.txt
Number of lines=2
Number of
Words=4Number of
character=26 Number of
spaces=3
student@student:~/naveen$
Sample Program 6
Aim:Program to recognize a valid variable, which starts with a letter, followed by any
number of letters or digits.
Lex part
%{
#include"y.tab.h"
%}
%option noyywrap
%%
[a-zA-Z]+ return l;
[0-9]+ return d;
[\t] ;
Page 18
System Software Laboratory 18CSL66
\n return 0;
. return yytext[0];
%%
Yacc part
%{
#include<stdio.h>
%}
%token l d
%%
var:l s {printf("valid variable");return 0;}
s:s l
|s d
|;
%%
main()
{
printf("enter the variable");
yyparse();
}
yyerror()
{
printf("invalid variable");
exit(0);
}
Page 19
System Software Laboratory 18CSL66
Program No.1a: 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.
Program Objective :
%{
#include<stdio.h>
int id=0,op=0,b=0;
%}
%option noyywrap
%%
[a-zA-Z0-9]*[a-zA-Z]* {id++;printf("\t");ECHO;}
[+|-|*|/] {op++;printf("\t");ECHO;}
"(" b++;
")" b--;
%%
main()
{
printf("enter arthimetic expression \n");
yylex();
if((op+1==id) && b==0)
{
printf("valid expression\n");
printf("No of Identifers=%d\n",id);
printf("No of operators=%d\n",op);
}
else
printf("invalid expression\n");
}
Page 20
System Software Laboratory 18CSL66
Output 1
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter arthimetic expression
(1+2)
1 + 2
valid expression
No of Identifers=2
No of operators=1
Output 2
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter arthimetic expression
((1+2)*3)
1 + 2 * 3
valid expression
No of Identifers=3
No of operators=2
Output 3
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter arthimetic expression
((1+2)
1 + 2
invalid expression
Output 4
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter arthimetic expression
((1+2)*3
1 + 2 * 3
invalid expression
Page 21
System Software Laboratory 18CSL66
Program No.1b: Write YACC program to evaluate arithmetic expression
involving operators: +, -, *, and /.
lex part
%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return num;}
[\+\-\*\/] {return yytext[0];}
[)] {return yytext[0];}
[(] {return yytext[0];}
. {;}
\n {return 0;}
%%
yacc part
%{
#include<stdio.h>
#include<stdlib.h>
int yyerror();
int yylex();
%}
%token num
%left '+''-'
%left '*''/'
%%
input:exp{printf("%d\n",$$);exit(0);}
exp:exp'+'exp{$$=$1+$3;}
|exp'-'exp{$$=$1-$3;}
|exp'*'exp{$$=$1*$3;}
|exp'/'exp {if($3==0){printf("Divide by Zero\n");exit(0);} else
$$=$1/$3;}
|'('exp')'{$$=$2;}
|num{$$=$1;};
%%
int yyerror()
{
printf("error");
exit(0);
}
Page 22
System Software Laboratory 18CSL66
int main()
{
printf("enter expression\n");
yyparse();
}
Output1
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
(2+4)*(2-8)
-36
student@student:~/naveen$
Output2
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
5/0
Divide by Zero
Output3
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
(2*5)/5
2
Page 23
System Software Laboratory 18CSL66
Program Outcome
Viva Questions:
What is an Assembler?
Assembler for an assembly language, a computer program to
translate between lower-level representations of computer programs.
Page 24
System Software Laboratory 18CSL66
Program No. 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).
Program Objective :
lex part
%{
#include "y.tab.h"
%}
%%
a {return A;}
b {return B;}
. {return yytext[0];}
[\n] {return 0;}
%%
yacc part
%{
#include<stdio.h>
#include<stdlib.h>
int yylex();
int yyerror();
int count=0;
%}
%token A B
%%
s:A s{count++;}
|B
;
%%
int main()
{
int n;
printf("enter value for n\n");
scanf("%d",&n);
getchar();
printf("enter input string with a's and b's\n");
yyparse();
if(n==count)
printf("valid string\n");
Page 25
System Software Laboratory 18CSL66
else
yyerror();
return 0;
}
int yyerror()
{
printf("invalid string\n");
exit(0);
}
Output1
student@student-OptiPlex-390:~$ yacc -d program2.y
student@student-OptiPlex-390:~$ lex program2.l
student@student-OptiPlex-390:~$ cc y.tab.c lex.yy.c -ll
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
ab
valid string
Output2
student@student-OptiPlex-390:~$ ./a.out
enter value for n
2
enter input string with a's and b's
aab
valid string
Output3
student@student-OptiPlex-390:~$ ./a.out
enter value for n
0
enter input string with a's and b's
b
valid string
Output4
student@student-OptiPlex-390:~$ ./a.out
enter value for n
0
enter input string with a's and b's
ab
invalid string
Page 26
System Software Laboratory 18CSL66
Output5
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
aab
invalid string
Output6
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
acb
invalid string
student@student-OptiPlex-390:~$
Program Outcome:
Viva Questions:
Page 27
System Software Laboratory 18CSL66
Program No. 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$.
Program Objective :
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char prod[3][10]={"A->aBa","B->bB","B->@"};
char first[3][10]={"a","b","@"};
char follow[3][10]={"$","a","a"};
char table[3][3][10];
char input[10];
int top=-1;
char stack[25];
char curp[20];
char new1[10],new2[10],new3[10],newstr[10];
char table2 [4][3][10] =
{
"NT", "a","b",
"A", "aBa","Error",
"B", "Error","bB",
"B", "Error","e",
};
Page 28
System Software Laboratory 18CSL66
int numr(char c)
{
switch(c)
{
case 'A': return 1;
case 'B': return 2;
case 'a': return 1;
case 'b': return 2;
case '@': return 3;
}
return(1);
}
void calulatefollow()
{
char str1[20]="A->aBa",str2[20]="B->bB",str3[20]="B->@";
int n1=6,n2=5,n3=4,i,j,k;
printf("\nFOLLOW SET \n");
printf("\n FOLLOW(A)=$\n");
for(i=3;i<n1;i++)
{
if(str1[i]=='B')
printf("FOLLOW(B)=%c",str1[5]);
newstr[0]=str1[5];
}
}
void main()
{
char c;
int i,j,k,n,n1=6;
char str1[20]="A->aBa",str2[20]="B->bB",str3[20]="B->@";
for(i=0;i<3;i++)
for(j=0;j<4;j++)
strcpy(table[i][j],"e");
printf("\n Grammar:\n");
for(i=0;i<3;i++)
printf("%s\n",prod[i]);
printf("\nfirst(A)= {%s}\n",first[0]);
printf("\nfirst(B)= {%s,%s}\n",first[1],first[2]);
calulatefollow();
strcpy(table[0][0]," ");
strcpy(table[0][1],"a");
Page 29
System Software Laboratory 18CSL66
strcpy(table[0][2],"b");
strcpy(table[0][3],"$");
strcpy(table[1][0],"A");
strcpy(table[2][0],"B");
for(i=0;i<3;i++)
{
k=strlen(first[i]);
for(j=0;j<k;j++)
if(first[i][j]!='@')
strcpy(table[numr(prod[i][0])][numr(first[i][j])],prod[i]);
else
strcpy(table[numr(prod[i][0])][numr(follow[i][j])],prod[i]);
}
printf("\n \n");
printf("\n LL(1) PARSER TABLE \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%s\t",table[i][j]);
}
printf("\n");
}
printf("\n");
printf("\n \n");
printf("enter the input string terminated with $ to parse :- ");
scanf("%s",input);
for(i=0;input[i]!='\0';i++)
if((input[i]!='a')&&(input[i]!='b')&&(input[i]!='$'))
{
printf("invalid string");
exit(0);
}
if(input[i-1]!='$')
{
printf("\n\nInput String Entered Without End marker $");
exit(0);
}
push('$');
push('A');
i=0;
printf("\n\n");
printf(" stack\t Input \taction ");
printf("\n - \n");
Page 30
System Software Laboratory 18CSL66
while(input[i]!='$' && stack[top]!='$')
{
display();
printf("\t\t%s\t ",(input+i));
if (stack[top]==input[i])
{
printf("\tmatched %c\n",input[i]);
pop();
i++;
}
else
{
if(stack[top]>=65 && stack[top]<92)
{
strcpy(curp,table[numr(stack[top])][numr(input[i])]);
if(!(strcmp(curp,"e")))
{
printf("\n invalid string- Rejected\n");
exit(0);
}
else
{
printf(" \tapply production %s\n",curp);
if(curp[3]=='@')
pop();
else
{
pop();
n=strlen(curp);
for(j=n-1;j>=3;j--)
push(curp[j]);
}
}
}
}
display();
printf("\t\t%s\t ",(input+i));
printf("\n \n");
if(stack[top]=='$' && input[i]=='$' )
{
Page 31
System Software Laboratory 18CSL66
printf("\n valid string - Accepted\n");
}
else
{
printf("\ninvalid string- Rejected\n");
}
}
Output
student@student-OptiPlex-390:~$ cc program3.c
student@student-OptiPlex-390:~$ ./a.out
Grammar:
A->aBa
B->bB
B->@
first(A)= {a}
first(B)= {b,@}
FOLLOW SET
FOLLOW(A)=$
FOLLOW(B)=a
Page 32
System Software Laboratory 18CSL66
Program No.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.
Program Objective:
Theory
A parser is a compiler or interpreter component that breaks data into smaller elements
for easy translation into another language. A parser takes input in the form of a sequence
of tokens or program instructions and usually builds a data structure in the form of a
parse tree or an abstract syntax tree.
A parser's main purpose is to determine if input data may be derived from the start
symbol of the grammar.
Page 33
System Software Laboratory 18CSL66
Top-down Parsing
When the parser starts constructing the parse tree from the start symbol and then tries to
transform the start symbol to the input, it is called top-down parsing.
Backtracking:
It means, if one derivation of a production fails, the syntax analyzer restarts the process
using different rules of same production. This technique may process the input string
more than once to determine the right production.
Bottom-up Parsing
Bottom-up parsing starts with the input symbols and tries to construct the parse tree up to
the start symbol.
Shift-reduce parsing attempts to construct a parse tree for an input string beginning at
the leaves and working up towards the root. In other words, it is a process of
“reducing” (opposite of deriving a symbol using a production rule) a string w to the
start symbol of a grammar. At every (reduction) step, a particular substring matching
the RHS of a production rule is replaced by the symbol on the LHS of the production.
A general form of shift-reduce parsing is LR (scanning from Left to right and using
Right-most derivation in reverse) parsing, which is used in a number of automatic
parser generators like Yacc, Bison, etc.
Page 34
System Software Laboratory 18CSL66
#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();
int main()
{
printf("GRAMMAR is:\n E->E+T|T \nT->T*F|F\nF->(E)|id\n");
printf("Enter input string\n");
gets(a);
c=strlen(a);
printf("stack \t input \t action\n");
printf("------\t ------\t ------ \n");
printf("\n$%s\t%s$\t",stk,a);
for(k=0,i=0; j<c; k++,i++,j++)
{
if(a[j]=='i' && a[j+1]=='d')
{
strcpy(act,"SHIFT ");
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='\0';
a[j]=' ';
a[j+1]=' ';
printf("\n$%s\t%s$\t%sid",stk,a,act);
check();
}
else if(a[j]=='+'||a[j]=='*')
{
strcpy(act,"SHIFT ");
stk[i]=a[j];
stk[i+1]='\0';
a[j]=' ';
printf("\n$%s\t%s$\t%s%c",stk,a,act,stk[i]);
check();
}
else
{
printf("\nERROR IN INPUT\n");
break;
}
}
if(stk[0]=='E' && j==c)
printf("\n****SUCCESSFULL PARSING****\n");
Page 35
System Software Laboratory 18CSL66
else
printf("\n****FAILURE IN PARSING****\n");
}
void check()
{
strcpy(ac,"REDUCE F->id");
for(z=0; z<c; z++)
if(stk[z]=='i' && stk[z+1]=='d')
{
stk[z]='F';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
j++;
}
strcpy(ac,"REDUCE T->T*F");
for(z=0; z<c; z++)
if(stk[z]=='T' && stk[z+1]=='*' && stk[z+2]=='F')
{
stk[z]='T';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
strcpy(ac,"REDUCE T->F");
for(z=0; z<c; z++)
if(stk[z]=='F' )
{
stk[z]='T';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
}
strcpy(ac,"REDUCE E->E+T");
for(z=0; z<c; z++)
{
if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='T' && stk[z+3]!='*' && a[j+1]!='*')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
stk[z+3]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
Page 36
System Software Laboratory 18CSL66
else if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='T' && j==c)
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
else
break;
}
strcpy(ac,"REDUCE E->T");
for(z=0; z<c; z++)
if(stk[z]=='T' )
{
if(a[j+1]=='+'||a[j+1]=='\0')
{
stk[z]='E';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
}
else
break;
}
strcpy(ac,"REDUCE F->(E)");
for(z=0; z<c; z++)
if(stk[z]=='(' && stk[z+1]=='E' && stk[z+2]==')')
{
stk[z]='F';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
}
Page 37
System Software Laboratory 18CSL66
Output
student@localhost:~/naveen$ cc program4.c
student@localhost:~/naveen$ ./a.out
GRAMMAR is:
E->E+T|T
T->T*F|F
F->(E)|id
Enter input string
id+id*id
stack input action
- -
$ id+id*id$
$id +id*id$ SHIFT id
$F +id*id$ REDUCE F->id
$T +id*id$ REDUCE T->F
$E +id*id$ REDUCE E->T
$E+ id*id$ SHIFT +
$E+id *id$ SHIFT id
$E+F *id$ REDUCE F->id
$E+T *id$ REDUCE T->F
$E+T* id$ SHIFT *
$E+T*id $ SHIFT id
$E+T*F $ REDUCE F->id
$E+T $ REDUCE T->T*F
$E $ REDUCE E->E+T
****SUCCESSFULL PARSING****
student@localhost:~/naveen$
Page 38
System Software Laboratory 18CSL66
Program Outcome :
Viva Questions
Page 39
System Software Laboratory 18CSL66
Program No.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
Program Objective :
#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);
fprintf(fp2,"\nSUB R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
Page 40
System Software Laboratory 18CSL66
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);
}
Output
input.txt
T1 -B =?
T2 C + D
T3 T1 * T2
A T3 =?
student@localhost:~/naveen$ cc program5.c
student@localhost:~/naveen$ ./a.out
student@localhost:~/naveen$ cat output.txt
MOV R0,-B
MOV T1,R0
MOV R0,C
ADD R0,D
MOV T2,R0
MOV R0,T1
MUL R0,T2
MOV T3,R0
MOV R0,T3
MOV A,R0
MOV R0,T3
MOV A,R0
Page 41
System Software Laboratory 18CSL66
Program Outcome
Viva Questions:
Page 42
System Software Laboratory 18CSL66
Program No. 6a: Write a LEX program to eliminate comment lines in a C
program and copy the resulting program into a separate file.
Program Objective:
Page 43
System Software Laboratory 18CSL66
Output1
student@student:~$ lex program6.l
student@student:~$ cc lex.yy.c
student@student:~$ cat >a.c
#include<stdio.h>
main()
{
int a,b,c;
/* declaration */
printf(" ------------");
scanf(" -------- ");
// for reading
getch();
}
getch();
}
student@student:~$
Output2
student@student:~$ cat >a1.c
main()
{
int a,b,c;
printf(" ");
// simple comment
scanf(" -------- ") ;
// comment below scanf
getch();
/* multiple
comment */
// single line comment
}
Page 44
System Software Laboratory 18CSL66
student@student:~$ ./a.out a1.c b1.c
number of comment lines 4
student@student:~$ cat b1.c
main()
{
int a,b,c;
printf(" -------------- ");
scanf(" -------- ") ;
getch();
}
student@student:~$
Page 45
System Software Laboratory 18CSL66
Program No. 6b: WriteYACC 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 %s\n",yytext);return OP;}
[0-9]+ {yylval = atoi(yytext); printf("numbers is %d\n",yylval); return DIGIT;}
int|char|bool|float|void|for|do|while|if|else|return|void {printf("keyword
is%s\n",yytext);return KEY;}
[a-zA-Z0-9]+ {printf("identifier is %s\n",yytext);return ID;}
.;
%%
yacc part
%{
#include <stdio.h>
#include <stdlib.h>
int yyerror();
int yylex();
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++;}
;
%%
Page 46
System Software Laboratory 18CSL66
#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!");
return -1;
}
yyin = myfile;
do
{
yyparse();
}
while (!feof(yyin));
printf("Number of numbers = %d\n Number ofKeywords = %d\n Number of
Identifiers = %d\n Number of noperators = %d\n",dig, key,id, op);
}
int yyerror()
{
printf("error");
exit(0);
}
Output
input.c
void main()
{
int a;
float b;
char c;
char d;
int sum=40;
if(sum>=40)
printf("---pass--");
else
printf("---fail--");
}
Page 47
System Software Laboratory 18CSL66
student@localhost:~/naveen$ yacc -d program6b.y
student@localhost:~/naveen$ lex program6b.l
student@localhost:~/naveen$ cc y.tab.c lex.yy.c -ll
student@localhost:~/naveen$ ./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
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
student@localhost:~/naveen$
Page 48
System Software Laboratory 18CSL66
Program Outcome :
Viva Questions :
Non-Terminals:- These are syntactic variables in the grammar which represents a set
of strings the grammar is composed of. In a Parse tree all the inner nodes represents
the Non-Terminal symbols.
Page 49
System Software Laboratory 18CSL66
Program No. 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.
Program Objective:
Theory
Round Robin scheduling algorithm is one of the most popular scheduling algorithm which
can actually be implemented in most of the operating systems. This is the preemptive version
of first come first serve scheduling. The Algorithm focuses on Time Sharing
In this algorithm, every process gets executed in a cyclic way. A certain time slice is defined
in the system which is called time quantum. Each process present in the ready queue is
assigned the CPU for that time quantum, if the execution of the process is completed during
that time then the process will terminate else the process will go back to the ready queue and
waits for the next turn to complete the execution.
Some important characteristics of the Round Robin (RR) Algorithm are as follows:
Round Robin Scheduling algorithm resides under the category of Preemptive Algorithms.
This algorithm is one of the oldest, easiest, and fairest algorithms.
This Algorithm is a real-time algorithm because it responds to the event within a specific
time limit.
In this algorithm, the time slice should be the minimum that is assigned to a specific task
that needs to be processed. Though it may vary for different operating systems.
This is a hybrid model and is clock-driven in nature.
This is a widely used scheduling method in the traditional operating system.
Important terms
1. Completion Time It is the time at which any process completes its execution.
2. Turn Around Time This mainly indicates the time Difference between completion time
and arrival time. The Formula to calculate the same is: Turn Around Time = Completion
Time – Arrival Time
3. Waiting Time(W.T): It Indicates the time Difference between turn around time and burst
time. And is calculated as Waiting Time = Turn Around Time – Burst Time
Page 50
System Software Laboratory 18CSL66
Page 51
System Software Laboratory 18CSL66
/* Round Robin Program in C*/
#include<stdio.h>
int main()
{
int i,j,n,time,x,counter=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
x=n;
for(i=0;i<n;i++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",i+1);
scanf("%d",&at[i]);
scanf("%d",&bt[i]);
rt[i]=bt[i];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,i=0;x!=0;)
{
if(rt[i]<=time_quantum && rt[i]>0)
{
time+=rt[i];
rt[i]=0;
counter=1;
}
else if(rt[i]>0)
{
rt[i]-=time_quantum;
time+=time_quantum;
}
if(rt[i]==0 && counter==1)
{
x--;
printf("P[%d]\t|\t%d\t|\t%d\n",i+1,time-at[i],time-at[i]-bt[i]);
wait_time+=time-at[i]-bt[i];
turnaround_time+=time-at[i];
counter=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
Page 52
System Software Laboratory 18CSL66
i++;
else
i=0;
}
printf("\nAverage Waiting Time= %.2f\n",wait_time*1.0/n);
printf("Average Turnaround Time = %.2f",turnaround_time*1.0/n);
return 0;
}
Output1
student@student:~/naveen$ cc program7rr.c
student@student:~/naveen$ ./a.out
Enter Total Process: 3
Enter Arrival Time and Burst Time for Process Process Number 1 :0 7
Enter Arrival Time and Burst Time for Process Process Number 2 :2 4
Enter Arrival Time and Burst Time for Process Process Number 3 :4 1
Enter Time Quantum: 3
Output2
student@student:~/naveen$ cc program7rr.c
student@student:~/naveen$ ./a.out
Enter Total Process: 4
Enter Arrival Time and Burst Time for Process Process Number 1 :0 10
Enter Arrival Time and Burst Time for Process Process Number 2 :1 4
Enter Arrival Time and Burst Time for Process Process Number 3 :2 5
Enter Arrival Time and Burst Time for Process Process Number 4 :3 3
Enter Time Quantum: 4
Page 53
System Software Laboratory 18CSL66
Average Waiting Time= 9.25
Average Turnaround Time = 14.75
student@student:~/naveen$
Output3
student@student:~/naveen$ cc program7rr.c
student@student:~/naveen$ ./a.out
Enter Total Process: 5
Enter Arrival Time and Burst Time for Process Process Number 1 :0 8
Enter Arrival Time and Burst Time for Process Process Number 2 :1 1
Enter Arrival Time and Burst Time for Process Process Number 3 :2 3
Enter Arrival Time and Burst Time for Process Process Number 4 :3 2
Enter Arrival Time and Burst Time for Process Process Number 5 :4 6
Enter Time Quantum: 3
Page 54
System Software Laboratory 18CSL66
/* Round Robin Program in Java */
import java.util.Scanner;
{
public static void main(String[] args)
{
int i,j,n,time,x,counter=0,time_quantum;
int wait_time=0,turnaround_time=0;
Scanner sn=new Scanner(System.in);
int[] at = new int[20];
int[] bt = new int[20];
int[] rt = new int[20];
System.out.println("Enter Total Process:\t ");
n=sn.nextInt();
x=n;
for(i=0;i<n;i++)
{
System.out.println("Enter Arrival Time for Process");
at[i]=sn.nextInt();
System.out.println("Enter burst time of process "+i);
bt[i]=sn.nextInt();
rt[i]=bt[i];
}
System.out.println("Enter Time Quantum:\t");
time_quantum=sn.nextInt();
System.out.println("\n\nProcess\t|Turnaround Time|Waiting Time");
for(time=0,i=0;x!=0;)
{
if(rt[i]<=time_quantum && rt[i]>0)
{
time+=rt[i];
rt[i]=0;
counter=1;
}
else if(rt[i]>0)
{
rt[i]-=time_quantum;
time+=time_quantum;
}
Page 55
System Software Laboratory 18CSL66
if(rt[i]==0 && counter==1)
{
x--;
System.out.print("process"+i+"\t");
System.out.print(time-at[i]+"\t");
System.out.print("\t");
System.out.print(time-at[i]-bt[i]);
System.out.println("\t");
wait_time+=time-at[i]-bt[i];
turnaround_time+=time-at[i];
counter=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
i++;
else
i=0;
}
System.out.println("\n Average Waiting Time="+wait_time*1.0/n);
System.out.println("Average Turnaround Time ="+turnaround_time*1.0/n);
}
}
Output 1
Enter Total Process:
3
Enter Arrival Time for Process
0
Enter burst time of process 0
7
Enter Arrival Time for Process
2
Enter burst time of process 1
4
Enter Arrival Time for Process
4
Enter burst time of process 2
1
Enter Time Quantum:
3
Page 56
System Software Laboratory 18CSL66
Process |Turnaround Time |Waiting Time
Process 2 3 2
Process 1 9 5
Process 0 12 5
Output2
Page 57
System Software Laboratory 18CSL66
Output3
Enter Total Process:
5
Enter Arrival Time for Process
0
Enter burst time of process 0
6
Enter Arrival Time for Process
0
Enter burst time of process 1
5
Enter Arrival Time for Process
0
Enter burst time of process 2
2
Enter Arrival Time for Process
0
Enter burst time of process 3
3
Enter Arrival Time for Process
0
Enter burst time of process 4
7
Enter Time Quantum:
2
Output 4
Enter Total Process:
6
Enter Arrival Time for Process
0
Enter burst time of process 0
4
Enter Arrival Time for Process
Page 58
System Software Laboratory 18CSL66
1
Enter burst time of process 1
5
Enter Arrival Time for Process
2
Enter burst time of process 2
2
Enter Arrival Time for Process
3
Enter burst time of process 3
1
Enter Arrival Time for Process
4
Enter burst time of process 4
6
Enter Arrival Time for Process
6
Enter burst time of process 5
3
Enter Time Quantum:
2
Page 59
System Software Laboratory 18CSL66
Shortest Remaining Time First (SRTF) Scheduling Algorithm
The Preemptive version of Shortest Job First(SJF) scheduling is known as Shortest Remaining
Time First (SRTF). With the help of the SRTF algorithm, the process having the smallest
amount of time remaining until completion is selected first to execute. So basically in SRTF,
the processes are scheduled according to the shortest remaining time.
However, the SRTF algorithm involves more overheads than the Shortest job first
(SJF)scheduling, because in SRTF OS is required frequently in order to monitor the CPU
time of the jobs in the READY queue and to perform context switching.
In the SRTF scheduling algorithm, the execution of any process can be stopped after a
certain amount of time. On arrival of every process, the short-term scheduler schedules
those processes from the list of available processes & running processes that have the
least remaining burst time.
After all the processes are available in the ready queue, then, No preemption will be
done and then the algorithm will work the same as SJF scheduling. In the Process
Control Block, the context of the process is saved, when the process is removed from the
execution and when the next process is scheduled. The PCB is accessed on the next
execution of this process
Advantages of SRTF
The main advantage of the SRTF algorithm is that it makes the processing of the jobs
faster than the SJF algorithm, mentioned it’s overhead charges are not counted.
Disadvantages of SRTF
In SRTF, the context switching is done a lot more times than in SJN due to more
consumption of the CPU's valuable time for processing. The consumed time of CPUthen
adds up to its processing time and which then diminishes the advantage of fast
processing of this algorithm.
Page 60
System Software Laboratory 18CSL66
/* Shortest Remaining Time Program in C*/
#include<stdio.h>
int n,qtum,pid[10],a[10],b[10],tt[10],avg[10];
int swt=0,stat=0;
float f_avg_turn_arnd_time=0.0,f_avg_wait_time=0.0;
int main()
{
int ch;
int a[10],b[10],x[10],i,smallest, count=0,time=0,n;
double avg=0,tt=0,end;
printf("enter the number of processes:\n");
scanf("%d",&n);
printf("enter arrival time\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the burst time \n");
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
x[i]=b[i];
b[9]=9999;
for(time=0;count!=n;time++)
{
smallest=9;
for(i=0;i<n;i++)
{
if(a[i]<=time && b[i]<b[smallest] && b[i]>0)
smallest=i;
}
b[smallest]--;
if(b[smallest]==0)
{
count++;
end=time+1;
avg=avg+end-a[smallest]-x[smallest];
tt=tt+end-a[smallest];
}
}
printf("\n average waiting time = %.2lf\n",avg/n);
printf("average turn around time = %.3lf",tt/n);
return 1;
}
Page 61
System Software Laboratory 18CSL66
Output 1
student@student:~/naveen$ cc program7srt.c
student@student:~/naveen$./a.out
enter the number of processes:
4
enter arrival time
0
1
2
4
enter the burst time
5
3
4
1
Output 2
student@student:~/naveen$ cc program7srt.c
student@student:~/naveen$./a.out
enter the number of processes:
5
enter arrival time
3
1
4
0
2
enter the burst time
1
4
2
6
3
Page 62
System Software and Operating System Laboratory 18CSL66
Output 3
student@student:~/naveen$ cc program7srt.c
student@student:~/naveen$./a.out
enter the number of processes:
5
enter arrival time
0
1
2
3
4
enter the burst time
8
4
2
1
3
Page 63
System Software and Operating System Laboratory 18CSL66
/*Shortest Remaining Time Program in Java */
import java.util.Scanner;
public class ShortestRemainingTime
{
public static void main(String[] args)
{
int i,n,smallest, count=0,time=0;
float avg=0,tt=0,end;
int[] a = new int[20];
int[] b = new int[20];
int[] x = new int[20];
int[] at = new int[20];
int[] pid = new int[20];
Scanner sn=new Scanner(System.in);
System.out.println("enter the number of processes:");
n=sn.nextInt();
for(i=0;i<n;i++)
{
System.out.println("Enter Arrival Time for Process :"+i);
a[i]=sn.nextInt();
}
for(i=0;i<n;i++)
{
System.out.println("Enter burst Time for Process :"+i);
b[i]=sn.nextInt();
}
for(i=0;i<n;i++)
x[i]=b[i];
b[9]=9999;
for(time=0;count!=n;time++)
{
smallest=9;
for(i=0;i<n;i++)
{
if(a[i]<=time && b[i]<b[smallest] && b[i]>0)
smallest=i;
} // end of for loop
b[smallest]--;
if(b[smallest]==0)
{
count++;
end=time+1;
avg=avg+end-a[smallest]-x[smallest];
tt=tt+end-a[smallest];
Page 64
System Software and Operating System Laboratory 18CSL66
}
}
// end of outer for loop
System.out.println("\n average waiting time = "+avg/n);
System.out.format("average turn around time= %.2f",tt/n);
}
Output1
enter the number of processes:
4
Enter Arrival Time for Process :0
0
Enter Arrival Time for Process :1
1
Enter Arrival Time for Process :2
2
Enter Arrival Time for Process :3
4
Enter burst Time for Process :0
5
Enter burst Time for Process :1
3
Enter burst Time for Process :2
4
Enter burst Time for Process :3
1
Output2
enter the number of processes:
5
Enter Arrival Time for Process :0
0
Enter Arrival Time for Process :1
1
Enter Arrival Time for Process :2
2
Enter Arrival Time for Process :3
3
Enter Arrival Time for Process :4
4
Page 65
System Software and Operating System Laboratory 18CSL66
Enter burst Time for Process :0
8
Enter burst Time for Process :1
4
Enter burst Time for Process :2
2
Enter burst Time for Process :3
1
Enter burst Time for Process :4
3
Output3
enter the number of processes:
6
Enter Arrival Time for Process :0
0
Enter Arrival Time for Process :1
1
Enter Arrival Time for Process :2
2
Enter Arrival Time for Process :3
3
Enter Arrival Time for Process :4
4
Enter Arrival Time for Process :5
5
Enter burst Time for Process :0
7
Enter burst Time for Process :1
5
Enter burst Time for Process :2
3
Enter burst Time for Process :3
1
Enter burst Time for Process :4
2
Enter burst Time for Process :5
1
Page 66
System Software and Operating System Laboratory 18CSL66
Program Outcome :
Viva Questions:
Page 67
System Software and Operating System Laboratory 18CSL66
Program No. 8: Design, develop and implement a C/C++/Java program to
implement Banker’s algorithm. Assume suitable input required to demonstrate
the results.
Program Objective :
To understand Deadlocks
To understand the Bankers algorithm
Theory
Page 68
System Software and Operating System Laboratory 18CSL66
printf("enter the allocation\n");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("enter the max \n");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("enter avialable resuruces\n");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
printf("enter new request details\n");
printf("enter new pid \n");
scanf("%d",&id);
printf("enter request for resuruces\n");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i]+=newr;
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])
else
Page 69
System Software and Operating System Laboratory 18CSL66
b=b-1;
}
if(b==r)
{
printf("\np%d is visited",j);
// put processes in to safe sequence array
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<n;k++)
printf("%3d",avail[k]); // print new allocation resources
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("request is not granted Dead lock occured\n");
printf("system is in un safe state\n");
goto y;
}
}
printf("\n system is in safe state\n");
printf(" safe sequence is ");
for(i=0;i<fl;i++)
printf("P%d",seq[i]);
y:
printf("\n process \t allocation \t max \t need\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
printf(" %3d",f[i].all[j]);
for(j=0;j<r;j++)
printf(" %3d",f[i].max[j]);
for(j=0;j<r;j++)
printf(" %3d",f[i].need[j]);
printf("\n");
}
}
Page 70
System Software and Operating System Laboratory 18CSL66
Output1
student@student:~/naveen$ cc program8.c
student@student:~/naveen$ ./a.out
enter the number of processess
5
enter the number of resources
3
enter the details of p 0
enter the allocation
010
enter the max
753
enter the details of p 1
enter the allocation
200
enter the max
322
enter the details of p 2
enter the allocation
302
enter the max
902
enter the details of p 3
enter the allocation
211
enter the max
222
enter the details of p 4
enter the allocation
002
enter the max
433
p 1 is visited(422)
p 3 is visited(633)
Page 71
System Software and Operating System Laboratory 18CSL66
p 4 is visited(635)
p 0 is visited(755)
p 2 is visited(1057)
Output2
student@student:~/naveen$ ./a.out
enter the number of processess
5
enter the number of resources
4
enter the details of p 0
enter the allocation
0012
enter the max
0012
enter the details of p 1
enter the allocation
1000
enter the max
1756
enter the details of p 2
enter the allocation
1354
enter the max
2356
enter the details of p 3
enter the allocation
0632
enter the max
0652
enter the details of p 4
enter the allocation
0014
Page 72
System Software and Operating System Laboratory 18CSL66
enter the max
0656
enter avialable resuruces
1520
enter new request details
enter new pid
0
enter request for resuruces
0110
p0 is visited(1532)
p2 is visited(2886)
p3 is visited(214118)
p 4 is visited(2141212)
p 1 is visited(3141212)
Output3
student@student:~/naveen$ cc program8.c
student@student:~/naveen$ ./a.out
enter the number of processess
4
enter the number of resources
3
enter the details of p 0
enter the allocation
101
enter the max
437
enter the details of p 1
enter the allocation
112
enter the max
214
enter the details of p 2
enter the allocation
Page 73
System Software and Operating System Laboratory 18CSL66
103
enter the max
133
enter the details of p 3
enter the allocation
200
enter the max
541
enter avialable resuruces
330
enter new request details
enter new pid
0
enter request for resuruces
220
Page 74
System Software and Operating System Laboratory 18CSL66
/* Banker’s Program in Java*/
import java.util.*;
public class Banker
{
static int safe[]=new int[20];
static boolean safety(int a[],int al[][],int need[][],int n1,int m1)
{
int n=n1;
int m=m1;
int nd[][]=new int[n][m];
int work[]=new int[m];
int all[][]=new int[n][m];
for(int i=0;i<m;i++)
work[i]=a[i];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
all[i][j]=al[i][j];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
nd[i][j]=need[i][j];
boolean fin[]=new boolean[n];
for(int i=0;i<n;i++)
fin[i]=false;
int check=0;
int check1=0;
do
{
for(int i=0;i<n;i++)
{
boolean flag=true;
if(fin[i]==false)
{
for(int j=0;j<m;j++)
{
if(work[j]<nd[i][j])
flag=false;
}
if(flag)
{
for(int j=0;j<m;j++)
work[j]+=all[i][j];
safe[check]=i;
check++;
fin[i]=true;
Page 75
System Software and Operating System Laboratory 18CSL66
}
}
}
check1++;
}
while(check<n && check1<n);
if(check>n)
return false;
else
return true;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n,m;
System.out.println("enter no. of processes:");
n=sc.nextInt();
System.out.println("enter no. of resources:");
m=sc.nextInt();
int a[]=new int[m];
for(int i=0;i<m;i++)
{
System.out.println("enter no. of available instances resources:"+i);
a[i]=sc.nextInt();
}
System.out.println("enter allocation of resources:");
int al[][]=new int[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
System.out.println("enter allocation instances of resources:"+j+"for processp"+i);
al[i][j]=sc.nextInt();
}
System.out.println("enter maximum of resources:");
int max[][]=new int[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
System.out.println("enter max instances of resources:"+j+"for process p"+i);
max[i][j]=sc.nextInt();
}
int need[][]=new int[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
Page 76
System Software and Operating System Laboratory 18CSL66
{
need[i][j]=max[i][j]-al[i][j];
}
if(safety(a,al,need,n,m))
{
System.out.println("System in Safe State");
System.out.println("System's Safe sequence:");
for(int i=0;i<n;i++)
System.out.print("p"+safe[i]+"\t");
}
else
System.out.println("System in UnSafe State");
}
}
Output 1
enter no. of processes:
5
enter no. of resources:
3
enter no. of available instances resources:0
3
enter no. of available instances resources:1
3
enter no. of available instances resources:2
2
enter allocation of resources:
enter allocation instances of resources: 0 for process p0
0
enter allocation instances of resources:1 for process p0
1
enter allocation instances of resources:2 for process p0
0
enter allocation instances of resources:0 for process p1
2
enter allocation instances of resources:1 for process p1
0
enter allocation instances of resources:2 for process p1
0
enter allocation instances of resources: 0 for process p2
3
enter allocation instances of resources:1 for process p2
0
enter allocation instances of resources:2 for process p2
2
Page 77
System Software and Operating System Laboratory 18CSL66
enter allocation instances of resources:0 for process p3
2
enter allocation instances of resources:1 for process p3
1
enter allocation instances of resources:2 for process p3
1
enter allocation instances of resources:0 for process p4
0
enter allocation instances of resources:1 for process p4
0
enter allocation instances of resources:2 for process p4
2
enter maximum of resources:
enter max instances of resources:0 for process p0
7
enter max instances of resources:1 for process p0
5
enter max instances of resources:2 for process p0
3
enter max instances of resources:0 for process p1
3
enter max instances of resources:1 for process p1
2
enter max instances of resources:2 for process p1
2
enter max instances of resources:0 for process p2
9
enter max instances of resources:1 for process p2
0
enter max instances of resources:2 for process p2
2
enter max instances of resources:0 for process p3
2
enter max instances of resources:1 for process p3
2
enter max instances of resources:2 for process p3
2
enter max instances of resources:0 for process p4
4
enter max instances of resources:1 for process p4
3
enter max instances of resources:2 for process p4
3
Page 78
System Software and Operating System Laboratory 18CSL66
System in Safe State
System's Safe sequence: p1 p3 p4 p0 p2
Output 2
enter no. of processes:
5
enter no. of resources:
4
enter no. of available instances resources:0
1
enter no. of available instances resources:1
5
enter no. of available instances resources:2
2
enter no. of available instances resources:3
0
enter allocation of resources:
enter allocation instances of resources:0 for process p0
0
enter allocation instances of resources:1 for process p0
0
enter allocation instances of resources:2 for process p0
1
enter allocation instances of resources:3 for process p0
2
enter allocation instances of resources:0 for process p1
1
enter allocation instances of resources:1 for process p1
0
enter allocation instances of resources:2 for process p1
0
enter allocation instances of resources:3 for process p1
0
enter allocation instances of resources:0 for process p2
1
enter allocation instances of resources:1 for process p2
3
enter allocation instances of resources:2 for process p2
5
enter allocation instances of resources:3 for process p2
4
enter allocation instances of resources:0 for process p3
0
enter allocation instances of resources:1 for process p3
Page 79
System Software and Operating System Laboratory 18CSL66
6
enter allocation instances of resources:2 for process p3
3
enter allocation instances of resources:3 for process p3
2
enter allocation instances of resources:0 for process p4
0
enter allocation instances of resources:1 for process p4
0
enter allocation instances of resources:2 for process p4
1
enter allocation instances of resources:3 for process p4
4
enter maximum of resources:
enter max instances of resources:0 for process p0
0
enter max instances of resources:1 for process p0
0
enter max instances of resources:2 for process p0
1
enter max instances of resources:3 for process p0
2
enter max instances of resources:0 for process p1
1
enter max instances of resources:1 for process p1
7
enter max instances of resources:2 for process p1
5
enter max instances of resources:3 for process p1
6
enter max instances of resources:0 for process p2
2
enter max instances of resources:1 for process p2
3
enter max instances of resources:2 for process p2
5
enter max instances of resources:3 for process p2
6
enter max instances of resources:0 for process p3
0
enter max instances of resources:1for process p3
6
enter max instances of resources:2 for process p3
5
Page 80
System Software and Operating System Laboratory 18CSL66
enter max instances of resources:3 for process p3
2
enter max instances of resources:0 for process p4
0
enter max instances of resources:1 for process p4
6
enter max instances of resources:2 for process p4
5
enter max instances of resources:3 for process p4
6
System in Safe State
System's Safe sequence: p0 p2 p3 p4 p1
Output 3
enter no. of processes:
5
enter no. of resources:
4
enter no. of available instances resources:0
1
enter no. of available instances resources:1
3
enter no. of available instances resources:2
1
enter no. of available instances resources:3
0
enter allocation of resources:
enter allocation instances of resources:0 for process p0
0
enter allocation instances of resources:1 for process p0
1
enter allocation instances of resources:2 for process p0
1
enter allocation instances of resources:3 for process p0
0
enter allocation instances of resources:0 for process p1
1
enter allocation instances of resources:1 for process p1
4
enter allocation instances of resources:2for process p1
4
enter allocation instances of resources:3 for process p1
1
enter allocation instances of resources:0 for process p2
Page 81
System Software and Operating System Laboratory 18CSL66
1
enter allocation instances of resources:1 for process p2
3
enter allocation instances of resources:2 for process p2
6
enter allocation instances of resources:3 for process p2
5
enter allocation instances of resources:0 for process p3
0
enter allocation instances of resources:1 for process p3
6
enter allocation instances of resources:2 for process p3
3
enter allocation instances of resources:3for process p3
2
enter allocation instances of resources:0 for process p4
0
enter allocation instances of resources:1 for process p4
0
enter allocation instances of resources:2 for process p4
1
enter allocation instances of resources:3 for process p4
4
enter maximum of resources:
enter max instances of resources:0 for process p0
0
enter max instances of resources:1 for process p0
2
enter max instances of resources:2for process p0
1
enter max instances of resources:3for process p0
0
enter max instances of resources:0for process p1
1
enter max instances of resources:1for process p1
6
enter max instances of resources:2for process p1
5
enter max instances of resources:3for process p1
2
enter max instances of resources:0for process p2
2
enter max instances of resources:1for process p2
3
Page 82
System Software and Operating System Laboratory 18CSL66
enter max instances of resources:2for process p2
6
enter max instances of resources:3for process p2
6
enter max instances of resources:0for process p3
0
enter max instances of resources:1for process p3
6
enter max instances of resources:2for process p3
5
enter max instances of resources:3for process p3
2
enter max instances of resources:0for process p4
0
enter max instances of resources:1for process p4
6
enter max instances of resources:2for process p4
5
enter max instances of resources:3for process p4
6
System in Safe State
System's Safe sequence:
p0 p3 p4 p1 p2
Output4
enter no. of processes:
5
enter no. of resources:
3
enter no. of available instances resources:0
2
enter no. of available instances resources:1
1
enter no. of available instances resources:2
0
enter allocation of resources:
enter allocation instances of resources:0 for process p0
1
enter allocation instances of resources:1 for process p0
1
enter allocation instances of resources:2 for process p0
2
enter allocation instances of resources:0 for process p1
2
Page 83
System Software and Operating System Laboratory 18CSL66
enter allocation instances of resources:1 for process p1
1
enter allocation instances of resources:2 for process p1
2
enter allocation instances of resources:0 for process p2
4
enter allocation instances of resources:1 for process p2
0
enter allocation instances of resources:2 for process p2
1
enter allocation instances of resources:0 for process p3
0
enter allocation instances of resources:1 for process p3
2
enter allocation instances of resources:2 for process p3
0
enter allocation instances of resources:0 for process p4
1
enter allocation instances of resources:1 for process p4
1
enter allocation instances of resources:2 for process p4
2
enter maximum of resources:
enter max instances of resources:0 for process p0
4
enter max instances of resources:1 for process p0
3
enter max instances of resources:2 for process p0
3
enter max instances of resources:0 for process p1
3
enter max instances of resources:1 for process p1
2
enter max instances of resources:2 for process p1
2
enter max instances of resources:0 for process p2
9
enter max instances of resources:1 for process p2
0
enter max instances of resources:2 for process p2
2
enter max instances of resources:0 for process p3
7
enter max instances of resources:1 for process p3
Page 84
System Software and Operating System Laboratory 18CSL66
5
enter max instances of resources:2 for process p3
3
enter max instances of resources:0 for process p4
1
enter max instances of resources:1 for process p4
1
enter max instances of resources:2 for process p4
2
System in Safe State
System's Safe sequence: p1 p4 p0 p2 p3
Program Outcome
Viva Questions
Define API’s
An application programming interface (API) is a source code based specification
intended to be used as an interface by software components to communicatewith
each other.
Page 85
System Software and Operating System Laboratory 18CSL66
Program No. 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.
Program Objective:
Theory
In a computer operating system that uses paging for virtual memory management, page
replacement algorithms decide which memory pages to page out, sometimes called swap out,
or write to disk, when a page of memory needs to be allocated.
Page replacement happens when a requested page is not in memory (page fault) and a free
page cannot be used to satisfy the allocation, either because there are none, or because the
number of free pages is lower than some threshold.
When the page that was selected for replacement and paged out is referenced again it has to be
paged in (read in from disk), and this involves waiting for I/O completion. This determines the
quality of the page replacement algorithm: the less time waiting for page-ins, the better the
algorithm.
A page replacement algorithm looks at the limited information about accesses to the pages
provided by hardware, and tries to guess which pages should be replaced to minimize the total
number of page misses, while balancing this with the costs (primary storage and processor
time) of the algorithm itself.
The page replacing problem is a typical online problem from the competitive analysis
perspective in the sense that the optimal deterministic algorithm is known.
LRU
LRU replaces the line in the cache that has been in the cache the longest with no reference to
it. It works on the idea that the more recently used blocks are more likely to be referenced
again. LRU is the most frequently used algorithm as it gives less number of page faults when
compared to the other algorithms.
Page 86
System Software and Operating System Laboratory 18CSL66
Characteristics of LRU
It has been observed that pages that have been recently heavily used will probably also be
heavily used in the upcoming instructions and this forms the basis for LRU.
When the page requested by the program is not present in the RAM, page fault occurs and then
if the page frame is full then we have to remove the page that has not been in use for the
longest period of time.
Can be implemented easily in a 2-way set associative mapping in which each line includes a
USE bit. The USE bit of the referenced line is set to 1 and that of the other line is set to 0.
When the set is full, we consider that block for replacement whose USE bit is zero.
Advantages of LRU
There is more overhead as we have to keep track of which pages were referenced.
It is difficult to implement as hardware assistance is required.
int main()
{
Page 87
System Software and Operating System Laboratory 18CSL66
int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1,
flag2, i, j, pos, faults = 0;
printf("Enter number of frames: ");
scanf("%d", &no_of_frames);
printf("Enter number of pages: ");
scanf("%d", &no_of_pages);
printf("Enter reference string: ");
for(i = 0; i < no_of_pages; ++i)
{
scanf("%d", &pages[i]);
}
for(i = 0; i < no_of_frames; ++i)
{
frames[i] = -1;
}
for(i = 0; i < no_of_pages; ++i)
{
flag1 = flag2 = 0;
for(j = 0; j < no_of_frames; ++j)
{
if(frames[j] == pages[i])
{
counter++;
time[j] = counter;
flag1 = flag2 = 1;
break;
}
}
if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j)
{
if(frames[j] == -1){
counter++;
faults++;
frames[j] = pages[i];
time[j] = counter;
flag2 = 1;
break;
}
}
}
if(flag2 == 0)
{
Page 88
System Software and Operating System Laboratory 18CSL66
pos = findLRU(time, no_of_frames);
counter++;
faults++;
frames[pos] = pages[i];
time[pos] = counter;
}
printf("\n");
for(j = 0; j < no_of_frames; ++j){
printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);
return 0;
}
Output1
student@student:~/naveen$ cc program9lru.c
student@student:~/naveen$ ./a.out
Enter number of frames: 3
Enter number of pages: 6
Enter reference string: 1 3 0 3 5 6
1 -1 -1
1 3 -1
1 3 0
1 3 0
5 3 0
5 3 6
Output2
student@student:~/naveen$ cc program9lru.c
student@student:~/naveen$ ./a.out
0 -1 -1 -1
0 1 -1 -1
0 1 7 -1
0 1 7 2
Page 89
System Software and Operating System Laboratory 18CSL66
3 1 7 2
3 1 7 2
3 1 7 2
3 1 7 2
0 1 7 2
0 1 7 3
Output3
student@student:~/naveen$ cc program9lru.c
student@student:~/naveen$ ./a.out
Enter number of frames: 3
Enter number of pages: 12
Enter reference string: 4 3 2 1 4 3 5 4 3 2 1 5
4 -1 -1
4 3 -1
4 3 2
1 3 2
1 4 2
1 4 3
5 4 3
5 4 3
5 4 3
2 4 3
2 1 3
2 1 5
Page 90
System Software and Operating System Laboratory 18CSL66
/* LRU Program in Java */
import java.util.Scanner;
public class program9lru
{
static int findLRU(int time[], int n)
{
int i, minimum = time[0], pos = 0;
return pos;
}
public static void main(String[] args)
{
int no_of_frames, no_of_pages, counter = 0, flag1, flag2, i, j, pos, faults = 0;
int[] frames = new int[20];
int[] pages = new int[20];
int[] time = new int[20];
Scanner sn=new Scanner(System.in);
Page 91
System Software and Operating System Laboratory 18CSL66
flag1 = flag2 = 0;
System.out.println("\n");
Page 92
System Software and Operating System Laboratory 18CSL66
}
System.out.println("\n\nTotal Page Faults ="+ faults);
}
}
Output1
Enter number of frames:
3
Enter number of pages:
6
Enter reference string:
130356
1 -1 -1
1 3 -1
1 3 0
1 3 0
5 3 0
5 3 6
Total Page Faults =5
Output2
Enter number of frames:
4
Enter number of pages:
10
Enter reference string:
0172327103
0 -1 -1 -1
0 1 -1 -1
0 1 7 -1
0 1 7 2
3 1 7 2
3 1 7 2
3 1 7 2
3 1 7 2
0 1 7 2
0 1 7 3
Total Page Faults =7
Page 93
System Software and Operating System Laboratory 18CSL66
Output3
Enter number of frames:
3
Enter number of pages:
12
Enter reference string:
432143543215
4 -1 -1
4 3 -1
4 3 2
1 3 2
1 4 2
1 4 3
5 4 3
5 4 3
5 4 3
2 4 3
2 1 3
2 1 5
Total Page Faults =10
Output 4
Enter number of frames:
3
Enter number of pages:
15
Enter reference string:
701203042303120
7 -1 -1
7 0 -1
7 0 1
2 0 1
2 0 1
2 0 3
2 0 3
4 0 3
4 0 2
4 3 2
0 3 2
0 3 2
0 3 1
2 3 1
Page 94
System Software and Operating System Laboratory 18CSL66
2 0 1
Total Page Faults =12
Page 95
System Software and Operating System Laboratory 18CSL66
FIFO Page replacement algorithms
Page replacement algorithms like FIFO are used when there is a new page request, and there is
not enough space in the main memory to allocate the new page.
Hence, a page replacement algorithm decides which page it should replace so that it can
allocate the memory for the new page. The steps of a page replacement can be summarized in
a flowchart:
First-in, first-out (FIFO) algorithm has a simple approach to this problem. We keep track of all
the pages by using a queue in the main memory. As soon as a page comes in, we’ll put it in the
queue and continue. In this way, the oldest page would always be in the first place of the
queue.
Now when a new page comes in and there is no space in the memory, we remove the first page
in the queue, which is also the oldest one. It repeats this process until the operating system has
page flow in the system.
Page 96
System Software and Operating System Laboratory 18CSL66
Page Fault
A Page fault is another important concept in page replacement algorithms. A page fault
occurs when a page requested by a program is not present in the main memory.
A page fault generates an alert for the operating system. The operating system then retrieves
the page from the secondary or virtual memory to the main memory. All the processes runin
the background.
Generally, this takes a few milliseconds; still, it has a significant impact on the performance of
the operating system. A high number of page faults can slow down the whole system.
Although page faults are common in modern days operating systems, a large number of page
faults may cause the program to crash or terminate unexpectedly.
The effectiveness of a page replacement algorithm is measured with the number of page
fault it generates. The more effective the page replacement algorithm is, the less the
number of page faults generated by the algorithm.
Page 97
System Software and Operating System Laboratory 18CSL66
/* FIFO Program in C*/
#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
return 0;
}
Page 98
System Software and Operating System Laboratory 18CSL66
Output1
student@student:~/naveen$ cc program9fifo.c
student@student:~/naveen$ ./a.out
Page Fault Is 5
student@student:~/naveen$
Output2
student@student:~/naveen$ cc program9fifo.c
student@student:~/naveen$ ./a.out
Page 99
System Software and Operating System Laboratory 18CSL66
Page Fault Is 6
student@student:~/naveen$
Output3
student@student:~/naveen$ cc program9fifo.c
student@student:~/naveen$ ./a.out
Page 100
System Software and Operating System Laboratory 18CSL66
/* FIFO Program in Java */
import java.util.Scanner;
public class program9fifo
{
public static void main(String[] args)
{
int i,j,n,no,k,avail,count=0;
int[] a = new int[20];
int frame[]; //declaring array
frame = new int[20]; // allocating memory to array
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
System.out.println("ENTER THE NUMBER OF PAGES");
n = in.nextInt();
System.out.println(" ENTER THE PAGE NUMBER :");
for( i=0; i<n; i++)
{
//reading array elements from the user
a[i]=in.nextInt();
}
System.out.println(" ENTER THE NUMBER OF FRAMES :");
no = in.nextInt();
for(i=0;i<no;i++)
frame[i]= -1; //intialize empty farmes to -1
j=0;
System.out.println("\tref string\t page frames\n");
for(i=0;i<n;i++) //5
{
System.out.println(a[i]); //1 3 0 3 5 6
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0) // if it is not page hit ,insert page page number into memory
{
frame[j]=a[i];
j=(j+1)%no; // pointer points to next frame
count++; // counts no of page fault
for(k=0;k<no;k++)
System.out.print("\t\t"+frame[k]);
}
System.out.println("\n");
Page 101
System Software and Operating System Laboratory 18CSL66
}
System.out.println("Page Fault Is "+count);
}
}
Output 1
ENTER THE NUMBER OF PAGES
6
1 1 -1 -1
3 1 3 -1
0 1 3 0
3
5 5 3 0
6 5 6 0
Page Fault Is 5
Output 2
ENTER THE NUMBER OF PAGES
12
4 4 -1 -1
3 4 3 -1
2 4 3 2
1 1 3 2
4 1 4 2
3 1 4 3
Page 102
System Software and Operating System Laboratory 18CSL66
5 5 4 3
4
3
2 5 2 3
1 5 2 1
5
Page Fault Is 9
Output 3
ENTER THE NUMBER OF PAGES
10
0 0 -1 -1 -1
1 0 1 -1 -1
7 0 1 7 -1
2 0 1 7 2
3 3 1 7 2
2
7
1
0 3 0 7 2
3
Page Fault Is 6
Output 4
ENTER THE NUMBER OF PAGES
15
Page 103
System Software and Operating System Laboratory 18CSL66
ref string page frames
7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
0
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
3
1 0 1 3
2 0 1 2
0
Page Fault Is 12
Program Outcome:
To implement FIFO
And LRU page replacement algorithms
Viva Questions:
Page 104
System Software and Operating System Laboratory 18CSL66
Viva Questions
1. Define System Software.
System software is computer software designed to operate the computer hardware and to
provide a platform for running application software. Eg: operating system, assembler, and
loader.
2. What is an Assembler?
Assembler for an assembly language, a computer program to translate between lower- level
representations of computer programs.
Yacc: - parser.yacc takes a concise description of a grammar and produces a C routine that can
parse that grammar.
4. Explain yyleng?
yyleng-contains the length of the string our lexer recognizes.
5. What is a Parser?
A Parser for a Grammar is a program which takes in the Language string as it's input and
produces either a corresponding Parse tree or an Error.
Page 105
System Software and Operating System Laboratory 18CSL66
12. Are Lexical Analysis and Parsing two different Passes?
These two can form two different passes of a Parser. The Lexical analysis can store all the
recognized tokens in an intermediate file and give it to the Parser as an input. However it is
more convenient to have the lexical Analyzer as a co routine or a subroutine which the Parser
calls whenever it requires a token.
Symbol Description
| OR (alternation)
() Group of
Subexpression
* 0 or more
Occurrences
? 0 or 1 Occurrence
+ 1 or more
Occurrences
{n,m} n- m Occurrences
15. If Context- free grammars can represent every regular expression, why do one needs R.E
at all?
Regular Expression are Simpler than Context- free grammars.
It is easier to construct a recognizer for R.E than Context-Free grammar.
Breaking the Syntactic structure into Lexical & non- Lexical parts provide
better front end for the Parser.
R.E are most powerful in describing the lexical constructs like identifiers,
Keywords etc while Context- free grammars in representing the nested block
structures of the Language.
16. What are the Parse Trees?
Parse trees are the Graphical representation of the grammar which filters out the choice for
replacement order of the Production rules.
Non-Terminals:- These are syntactic variables in the grammar which represents a set of strings
the grammar is composed of. In a Parse tree all the inner nodes represents the Non-Terminal
symbols.
Page 106
System Software and Operating System Laboratory 18CSL66
18. What are Ambiguous Grammars?
A Grammar that produces more than one Parse Tree for the same sentences or
the Production rules in a grammar is said to be ambiguous.
The function vfork has the same calling sequence and same return values as fork. But
the sema ntics of the two functions differ. vfork is intended to create a new process when
the purpose of the new process is to exec a new program.
Page 107
System Software and Operating System Laboratory 18CSL66
be used as an interface by software components to communicate with each other.
Page 108