Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

System Software 18csl66 - Ss and Os Lab Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 117

Best VTU Student Companion App You Can Get

DOWNLOAD NOW AND GET


Instant VTU Updates, Notes, Question Papers,
Previous Sem Results (CBCS), Class Rank, University Rank,
Time Table, Students Community, Chat Room and Many
More

CLICK BELOW TO DOWNLOAD VTU CONNECT APP


IF YOU DON’T HAVE IT

* Visit https://vtuconnect.in for more info. For any queries or questions wrt our
platform contact us at: support@vtuconnect.in
Download & Share VTU Connect App Now From Google Play Store

ATME COLLEGE OF ENGINEERING


13th KM Stone, Bannur Road, Mysore - 560 028

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


(ACADEMIC YEAR 2020-21)

LABORATORY MANUAL

SUBJECT: SYSTEM SOFTWARE LABORATORY

SUBJECT CODE: 18CSL66

SEMESTER: VI

2018 CBCS Scheme

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
INSTITUTIONAL MISSION AND VISION

Objectives
• To provide quality education and groom top-notch professionals, entrepreneurs and
leaders for different fields of engineering, technology and management.
• To open a Training-R & D-Design-Consultancy cell in each department, gradually
introduce doctoral and postdoctoral programs, encourage basic & applied research in
areas of social relevance, and develop the institute as a center of excellence.
• To develop academic, professional and financial alliances with the industry as well as
the academia at national and transnational levels.
• To develop academic, professional and financial alliances with the industry as well as
the academia at national and transnational levels.
• To cultivate strong community relationships and involve the students and the staff in
local community service.
• To constantly enhance the value of the educational inputs with the participation of
students, faculty, parents and industry.

Vision
• Development of academically excellent, culturally vibrant, socially responsible and
globally competent human resources.

Mission
• To keep pace with advancements in knowledge and make the students competitive and
capable at the global level.
• To create an environment for the students to acquire the right physical, intellectual,
emotional and moral foundations and shine as torch bearers of tomorrow's society.
• To strive to attain ever-higher benchmarks of educational excellence.

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
Department of Computer Science & Engineering

Vision of the Department

• To develop highly talented individuals in Computer Science and Engineering to deal


with real world challenges in industry, education, research and society.

Mission of the Department

• To inculcate professional behavior, strong ethical values, innovative research


capabilities and leadership abilities in the young minds & to provide a teaching
environment that emphasizes depth, originality and critical thinking.

• Motivate students to put their thoughts and ideas adoptable by industry or to pursue
higher studies leading to research.

Program outcomes (POs)


Engineering Graduates will be able to:

• PO1. Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution of complex
engineering problems.

• 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.

• PO3. Design/development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.

• PO4. Conduct investigations of complex problems: Use research-based knowledge


and research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.

• PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources,
and modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.

• 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

• PO7. Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

• PO8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
• PO9. Individual and team work: Function effectively as an individual, and as a
member or leader in diverse teams, and in multidisciplinary settings.

• PO10. Communication: Communicate effectively on complex engineering activities


with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.

• PO11. Project management and finance: Demonstrate knowledge and understanding


of the engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.

• 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.

Program Specific Outcomes (PSOs)

1. PSO1: Ability to apply skills in the field of algorithms, database design, web design,
cloud computing and data analytics.
2. PSO2: Apply knowledge in the field of computer networks for building network and
internet based applications.

Program Educational Objectives (PEOs):

1. Empower students with a strong basis in the mathematical, scientific and engineering
fundamentals to solve computational problems and to prepare them for employment,
higher learning and R&D.

2. Gain technical knowledge, skills and awareness of current technologies of computer


science engineering and to develop an ability to design and provide novel engineering
solutions for software/hardware problems through entrepreneurial skills.

3. Exposure to emerging technologies and work in teams on interdisciplinary projects


with effective communication skills and leadership qualities.

4. Ability to function ethically and responsibly in a rapidly changing environment by


applying innovative ideas in the latest technology, to become effective professionals in
Computer Science to bear a life-long career in related areas.

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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$

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.

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store

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.
Study Experiment / Project:
NIL
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.
• All laboratory experiments, excluding the first, are to be included for practical
examination.
• Experiment distribution
o For questions having only one part: Students are allowed to pick one
experiment from thelot and are given equal opportunity.
o For questions having part A and B: Students are allowed to pick one
experiment frompart A and one experiment from part B and are given
equal opportunity.
• Change of experiment is allowed only once and marks allotted for procedure part
to be madezero.
• Marks Distribution (Subjected to change in accoradance with university regulations)
a) For questions having only one part – Procedure + Execution + Viva-Voce:
15+70+15 =100 Marks
b) For questions having part A and B
1. Part A – Procedure + Execution + Viva = 4 + 21 + 5 = 30 Marks
2. Part B – Procedure + Execution + Viva = 10 + 49+ 11 = 70 Marks

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
CONTENTS LIST

SL. EXPERIMENT NAME PAGE


NO NO
1. CHAPTER 1: Introduction to LEX 1
2. CHAPTER 2: Introduction to YACC 6
3. CHAPTER 3: Introduction to UNIX 9
4. CHAPTER 4: Introduction to Operating System 11
5. CHAPTER 5: Sample LEX and YACC programs 15
6. Program 1 :
a) Write a LEX program to recognize valid arithmetic 20
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 22
involving operators: +, -, *, and /
7. Program 2 : Develop, Implement and Execute a program using YACC
tool to recognize all strings ending with b preceded by n 25
a’s using the grammar an b (note: input n value)
8. Program 3: Design, develop and implement YACC/C program to
construct Predictive / LL(1) Parsing Table for the grammar rules: A 28
→aBa , B →bB | . Use this table to parse the
sentence: abba$
9. Program 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: 33
id + id * id.
10. Program 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 40

T3 = T1 + T2

A = T3

11. Program 6 :
a) Write a LEX program to eliminate comment lines in a C 43

program and copy the resulting program into a separate file.


b)Write YACC program to recognize valid identifier, operators 46
and keywords in the given text (C program) file.

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store

12. Program 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 50
algorithm
13. Program 8: Design, develop and implement a C/C++/Java program to
implement Banker’s algorithm. Assume suitable input required to 68
demonstrate the results
14. Program 9: Design, develop and implement a C/C++/Java program to
implement page replacement algorithms LRU and FIFO. Assume 86
suitable input required to demonstrate the results.
15. Viva Questions and Answers 105

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66

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.

Steps in writing LEX Program:

1st step: Using gedit create a file with extension .l

For example: program1.l

2nd Step: lex program1.l

3rd Step: cc lex.yy.c –ll

4th Step: ./a.out

Structure of LEX source program:


Copied to the beginning of C code

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:

• Specify the pattern-associated actions in a form that Lex can understand.


• Run Lex over this file to generate C code for the scanner.
• Compile and link the C code to produce the executable scanner.

DEPT OF CSE, ATMECE, MYSURU Page 1

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

Global C and Lex declarations:

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.

We'll also perform token declarations of Lex.


%{

int wordCount = 0;

%}

chars [A-za-z\_\'\.\"]

numbers ([0-9])+

delim [" "\n\t] whitespace {delim}+ words {chars}+

%%

The double percent sign implies the end of this section and the beginning of the second of
the three sections in Lex programming.

Lex rules for matching patterns:

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.

{words} { wordCount++; /*increase the word count by one*/ }

{whitespace} { /* do nothing*/ }

{numbers} { /* one may want to add some processing here*/ }

%%

DEPT OF CSE, ATMECE, MYSURU Page 2

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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*/
printf(" No of words: %d\n", wordCount);
}
int yywrap()

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

Putting it all together:

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.

Here are some of Lex's flags:

• -c Indicates C actions and is the default.


• -t Causes the lex.yy.c program to be written instead to standard output.
• -v Provides a two-line summary of statistics.
• -n Will not print out the -v summary
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
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

DEPT OF CSE, ATMECE, MYSURU Page 3

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

DEPT OF CSE, ATMECE, MYSURU Page 4

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66
^ 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 *,+
Examples of regular expressions

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

Examples of token declarations

Token Associated expression Meaning


number ([0-9])+ 1 or more occurrences
chars [A-Za- z] Any character
blank "" A blank space
word (chars)+ 1 or more occurrences
of chars
variable (chars)+(number)*(chars)*( number)*

DEPT OF CSE, ATMECE, MYSURU Page 5

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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:

1st step: Using gedit editor create a file with extension y.


For example: program1.y

2nd Step: yacc –d program1.y

3rd Step: lex program1.l

4th Step: cc y.tab.c lex.yy.c -ll

5th Step: /a.out

DEPT OF CSE, ATMECE, MYSURU Page 6

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

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.

1stCol 2ndCol 3rdCol 4thCol

DEFINITION SECTION
%%
RULE SECTION
%%
CODE SECTION

%% is a delimiter to the mark the beginning of the Rule 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

DEPT OF CSE, ATMECE, MYSURU Page 7

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

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.

DEPT OF CSE, ATMECE, MYSURU Page 8

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66
CHAPTER 3
Introduction to UNIX
Basic UNIX commands
Folder/Directory Commands and Options

Action UNIX options & filespec

Check current Print Working Directory Pwd

Return to user's home folder Cd


Up one folder cd ..
Make directory mkdir proj1
Remove empty directory rmdir/usr/sam
Remove directory-recursively rm -r

File Listing Commands and Options

Action UNIX options & filespec


List directory tree- recursively ls –r
List last access dates of files, with hidden files ls -l –a
List files by reverse date ls -t -r *.*
List files verbosely by size of file ls -l -s *.*
List files recursively including contents of other ls -R *.*
Directories
List number of lines in folder wc -l *.xtumlsed -n '$='
List files with x anywhere in the name ls | grep x

File Manipulation Commands and Options

Action UNIX options&filespec


Create new(blank)file touch afilename
Copy old file to new file. -p preserve file attributes cp old.file new.file
e.g. ownership and edit dates)-r copy recursively through
directory structure -a archive, combines the flags-p – R and-d
Move old. file(-i interactively flag prompts before overwriting mv –i old.file/tmp
files)
Remove file(- intention) rm –i sam.txt
Compare two files and show differences diff

DEPT OF CSE, ATMECE, MYSURU Page 9

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66
File Utilities

Action UNIX options & filespec


View a file vi file.txt
Concatenate files cat file1file2 to standard
Counts- lines,-words, and- characters in a file wc - l
Displays line-by- line differences between pairs of text files. diff
Calculator bc
calendar for September, 1752 (when leap years began) cal 9 1752

Controlling program execution for C-shell

& Run job in background


^c Kill job in foreground
^z Suspend job in foreground
Fg Restart suspended job in foreground
Bg Run suspended job in background
; Delimit commands on same line
() Group commands on same line
! re-run earlier commands from history list
jobs List current jobs

Controlling program input/output for C-shell

| Pipe output to input

> Redirect output to a storage file

< Redirect input from a storage file

>> Append redirected output to a storage file

tee Copy input to both file and next program in pipe


Make file record of al terminal activity
script

DEPT OF CSE, ATMECE, MYSURU Page 10

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

• Data section which contains globalvariables


• 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
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.

DEPT OF CSE, ATMECE, MYSURU Page 11

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66
The different scheduling algorithms are

• FCFS: First Come First Served Scheduling


• SJF: Shortest Job First Scheduling
• SRTF: Shortest Remaining Time First Scheduling
• Priority Scheduling
• Round Robin Scheduling
• Multilevel Queue Scheduling
• Multilevel Feedback Queue Scheduling

These algorithms are either non-preemptive or preemptive. Non-preemptive algorithms are


designed so that once a process enters the running state; it cannot be preempted until it completes
its allotted time, whereas the preemptive scheduling is based on priority where a scheduler may
preempt a low priority running process anytime when a high priority process enters into a ready
state.

First Come First Serve Scheduling


In the "First come first serve" scheduling algorithm, as the name suggests, the process which
arrives first, gets executed first, or we can say that the process which requests the CPU first, gets
the CPU allocated first.

• 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 selects process
from the head of the queue.
• A perfect real life example of FCFS scheduling is buying tickets at ticket counter.

Least Recently Used (LRU) page


The Least Recently Used (LRU) page replacement policy replaces the page that has not been
used for the longest period of time. It is one of the algorithms that were made to approximate if
not better the efficiency of the optimal page replacement algorithm. The optimal algorithm
assumes the entire reference string to be present at the time of allocation and replaces the page that
will not be used for the longest period of time.

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 Next (SJN)

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.

DEPT OF CSE, ATMECE, MYSURU Page 12

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

Shortest Remaining Time First (SRTF) Scheduling Algorithm


• This Algorithm is the preemptive version of SJF scheduling. In SRTF, the execution of
the process can be stopped after certain amount of time. At the arrival of every process, the
short term scheduler schedules the process with the least remaining burst time among the
list of available processes and the running process.
• Once all the processes are available in the ready queue, No preemption will be done and
the algorithm will work as SJF scheduling. The context of the process is saved in
the Process Control Block when the process is removed from the execution and the next
process is scheduled. This PCB is accessed on the next execution of this process.

Round Robin Scheduling Algorithm


• 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.
Multiple-Level Queues Scheduling
Multiple-level queues are not an independent scheduling algorithm. They make use of other
existing algorithms to group and schedule jobs with common characteristics.
• Multiple queues are maintained for processes with common characteristics.
• Each queue can have its own scheduling algorithms.
• Priorities are assigned to each queue.
For example, CPU-bound jobs can be scheduled in one queue and all I/O-bound jobs in another
queue. The Process Scheduler then alternately selects jobs from each queue and assigns them to
the CPU based on the algorithm assigned to the queue.
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

DEPT OF CSE, ATMECE, MYSURU Page 13

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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 deciding whether
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.

DEPT OF CSE, ATMECE, MYSURU Page 14

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66
CHAPTER 5
Sample Lex and Yacc Programs
Examples of sample Lex Program and Yacc Programs

Sample Program 1

Aim:program to count number of numbers and characters

%{
#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

Aim:program to count number of words

%{
#include<stdio.h>
int wc=0;
%}
%option noyywrap
%%
[^ \t\n]+ wc++;
%%

DEPT OF CSE, ATMECE, MYSURU Page 15

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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
ATME Colllege of Engineering
num of words 4

Sample Program 3

Aim: program to count number of vowels and consonants

%{
#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
ATME College of Engineering
num of vowels 11
no of consonants 13
student@student:~/naveen$

Sample Program 4

Aim: program to count number of comment lines

%{
#include<stdio.h>
int countcomment=0;
%}

DEPT OF CSE, ATMECE, MYSURU Page 16

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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
// ATME College of Engineering

/* SJCE College of Engineering


Mysuru */

// this is ssos lab

/* Welcome to
Mysuru City */

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)
{

DEPT OF CSE, ATMECE, MYSURU Page 17

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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
atme 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
atme college of engineering
sjce college of engineering
student@student:~/naveen$ ./a.out b.txt
Number of lines=2
Number of words=8
Number of character=56
Number of spaces=6
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] ;

DEPT OF CSE, ATMECE, MYSURU Page 18

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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);
}

student@student:~/naveen$ yacc –d 4a.y


student@student:~/naveen$ lex a.l
student@student:~/naveen$ cc y.tab.c lex.yy.c –ll
student@student:~/naveen$ ./a.out
enter the variable
a
valid variable
student@student:~/naveen$ yacc –d 4a.y
student@student:~/naveen$ lex a.l
student@student:~/naveen$ cc y.tab.c lex.yy.c –ll
student@student:~/naveen$ ./a.out
enter the variable
1
invalid variable

DEPT OF CSE, ATMECE, MYSURU Page 19

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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 :

• Understand the working of the lex program.


• Understand regular expression and identifiers.
• Understand the working of the yacc program.

%{
#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");
}

DEPT OF CSE, ATMECE, MYSURU Page 20

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 21

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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);
}

DEPT OF CSE, ATMECE, MYSURU Page 22

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 23

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66

Program Outcome

• To implement rules ,definition, code section of the lex program


• To implement the use of y.tab.h
• To implement tokens.
• To recognize the valid arithmetic expression
• To evaluate the arithmetic expression

Viva Questions:

• 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.

• What is an Assembler?
Assembler for an assembly language, a computer program to
translate between lower-level representations of computer programs.

DEPT OF CSE, ATMECE, MYSURU Page 24

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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 :

• To understand grammar and use of given in the program


• To understand the conditions used to implement the grammar

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");
DEPT OF CSE, ATMECE, MYSURU Page 25

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 26

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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:

• To implement rules, definition, code section of the lex program


• To implement the use of y.tab.h
• To implement tokens.
• To recognize the valid arithmetic expression
• To evaluate the arithmetic expression

Viva Questions:

• Explain lex and yacc tools


Lex: - scanner that can identify those tokens
Yacc: - parser.yacc takes a concise description of a grammar and
produces a C routine that can parse that grammar.
• Explain yyleng?
yyleng-contains the length of the string our lexer recognizes.
• What is a Parser?
A Parser for a Grammar is a program which takes in the Language
string as it's input and

DEPT OF CSE, ATMECE, MYSURU Page 27

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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 :

• To understand Predictive parsing table


• To understand the grammar rules validated using predictive parsing table.

#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",
};

void push(char item)


{
stack[++top]=item;
}
void pop()
{
top=top-1;;
}
void display()
{
int i;
for(i=top;i>=0;i--)
printf("%c",stack[i]);
}

DEPT OF CSE, ATMECE, MYSURU Page 28

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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");

DEPT OF CSE, ATMECE, MYSURU Page 29

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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");

DEPT OF CSE, ATMECE, MYSURU Page 30

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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]=='$' )
{

DEPT OF CSE, ATMECE, MYSURU Page 31

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

LL(1) PARSER TABLE


a b
A A->aBa e
B B->@ B->bB

enter the input string terminated with $ to parse :- abba$


stack Input action
-
A$ abba$ apply production A->aBa
aBa$ abba$ matched a
Ba$ bba$ apply production B->bB
bBa$ bba$ matched b
Ba$ ba$ apply production B->bB
bBa$ ba$ matched b
Ba$ a$ apply production B->@
a$ a$ matched a
$ $
-
valid string – Accepted
student@student-OptiPlex-390:~$

DEPT OF CSE, ATMECE, MYSURU Page 32

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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:

• To understand the shift reduce parsing technique


• To understand the behavior of input by using Shift reduce parsing
• To validate the grammar using shift reduce parsing

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.

• Syntax analyzers follow production rules defined by means of context-free grammar.


The way the production rules are implemented (derivation) divides parsing into two
types: top-down parsing and bottom-up parsing.

DEPT OF CSE, ATMECE, MYSURU Page 33

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

Recursive descent parsing:

It is a common form of top-down parsing. It is called recursive as it uses recursive procedures to


process the input. Recursive descent parsing suffers from backtracking.

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 (Bottom-up Parsing)

• 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.

DEPT OF CSE, ATMECE, MYSURU Page 34

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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");

DEPT OF CSE, ATMECE, MYSURU Page 35

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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;
}

DEPT OF CSE, ATMECE, MYSURU Page 36

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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;
}
}

DEPT OF CSE, ATMECE, MYSURU Page 37

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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$

DEPT OF CSE, ATMECE, MYSURU Page 38

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66

Program Outcome :

• To accept the input then to shift


• To reduce it to a specified term

Viva Questions

• What is the Lexical Analysis?


The Function of a lexical Analyzer is to read the input stream representing the
Source program, one character at a time and to translate it into valid tokens

• How can we represent a token in a language?


The Tokens in a Language are represented by a set of Regular Expressions.

A regular expression specifies a set of strings to be matched. It contains text


characters and operator characters. The Advantage of using regular expression is
that a recognizer can be automatically generated.

DEPT OF CSE, ATMECE, MYSURU Page 39

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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 :

• To understand a machine code


• To understand the use of a statement to generate machine code
• To see the input of statement given is seen in the form of the machine code

#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);
}

DEPT OF CSE, ATMECE, MYSURU Page 40

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 41

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66

Program Outcome

• To implement a c program to generate a machine code


• To accept the input in a separate file and display it in a separate file

Viva Questions:

• 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.
• What are the Advantages of using Context-Free grammars?
It is precise and easy to understand.
It is easier to determine syntactic ambiguities and conflicts in the
grammar.
• 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 or
block structures of the Language.

DEPT OF CSE, ATMECE, MYSURU Page 42

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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:

• To understand file handling using lex and yacc


%{ #include<stdio.h>
int yyerror();
int yylex();
int c_count=0;
%}
%option noyywrap
%%
"/*"[^"*/"]*"*/" c_count++;
"//".* c_count++;
%%
int main(int argc,char **argv)
{
FILE *f1,*f2;
if(argc>1)
{
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 for writing
if(!f2) // not able to open file
{
printf("file error\n");
exit(1);
}
yyout=f2;
yylex();
printf("number of comment lines%d\n",c_count);
}
return 0;
}

DEPT OF CSE, ATMECE, MYSURU Page 43

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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();
}

student@student:~$ ./a.out a.c b.c


number of comment lines 2
student@student:~$ cat b.c
#include<stdio.h>
main()
{
int a,b,c;

printf(" ----------- ");


scanf("-------- ");

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
}

DEPT OF CSE, ATMECE, MYSURU Page 44

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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:~$

DEPT OF CSE, ATMECE, MYSURU Page 45

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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++;}
;
%%

DEPT OF CSE, ATMECE, MYSURU Page 46

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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--");
}

DEPT OF CSE, ATMECE, MYSURU Page 47

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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$

DEPT OF CSE, ATMECE, MYSURU Page 48

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66

Program Outcome :

• To implement a lex and yacc program to access a file


• To count the number of identifiers operators and keywords in

Viva Questions :

• 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.

• What are Terminals and non-Terminals in a grammar?


Terminals: - All the basic symbols or tokens of which the language is composed of
are called Terminals. In a Parse Tree the Leafs represents the Terminal Symbol.

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.

DEPT OF CSE, ATMECE, MYSURU Page 49

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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:

• To understand the concept of shortest remaining job first


• To understand the concept of round robin

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

DEPT OF CSE, ATMECE, MYSURU Page 50

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66

Graphical Representation of Round Robin Algorithm

DEPT OF CSE, ATMECE, MYSURU Page 51

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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)

DEPT OF CSE, ATMECE, MYSURU Page 52

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

Process |Turnaround Time|Waiting Time


P[3] | 3 | 2
P[2] | 9 | 5
P[1] | 12 | 5

Average Waiting Time= 4.00


Average Turnaround Time = 8.00
student@student:~/naveen$

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

Process |Turnaround Time|Waiting Time


P[2] | 7 | 3
P[4] | 12 | 9
P[3] | 18 | 13
P[1] | 22 | 12

DEPT OF CSE, ATMECE, MYSURU Page 53

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

Process |Turnaround Time|Waiting Time


P[2] | 3 | 2
P[3] | 5 | 2
P[4] | 6 | 4
P[5] | 14 | 8
P[1] | 20 | 12

Average Waiting Time= 5.60


Average Turnaround Time = 9.60
student@student:~/naveen$

DEPT OF CSE, ATMECE, MYSURU Page 54

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66
/* Round Robin Program in Java */

import java.util.Scanner;

public class RoundRobin

{
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;
}

DEPT OF CSE, ATMECE, MYSURU Page 55

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 56

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software Laboratory 18CSL66
Process |Turnaround Time |Waiting Time
Process 2 3 2
Process 1 9 5
Process 0 12 5

Average Waiting Time=4.0


Average Turnaround Time =8.0

Output2

Enter Total Process:


4
Enter Arrival Time for Process
0
Enter burst time of process 0
10
Enter Arrival Time for Process
1
Enter burst time of process 1
4
Enter Arrival Time for Process
2
Enter burst time of process 2
5
Enter Arrival Time for Process
3
Enter burst time of process 3
3
Enter Time Quantum:
3

Process |Turnaround Time |Waiting Time


Process 3 9 6
Process 1 15 11
Process 2 16 11
Process 0 22 12

Average Waiting Time=10.0


Average Turnaround Time =15.5

DEPT OF CSE, ATMECE, MYSURU Page 57

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

Process |Turnaround Time |Waiting Time


Process 2 6 4
Process 3 15 12
Process 0 19 13
Process 1 20 15
Process 4 23 16

Average Waiting Time=12.0


Average Turnaround Time =16.6

Output 4
Enter Total Process:
6
Enter Arrival Time for Process
0
Enter burst time of process 0
4
Enter Arrival Time for Process

DEPT OF CSE, ATMECE, MYSURU Page 58

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

Process |Turnaround Time |Waiting Time


Process 2 4 2
Process 3 4 3
Process 0 13 9
Process 5 12 9
Process 1 18 13
Process 4 17 11

Average Waiting Time=7.83


Average Turnaround Time =11.33

DEPT OF CSE, ATMECE, MYSURU Page 59

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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 CPU then
adds up to its processing time and which then diminishes the advantage of fast
processing of this algorithm.

DEPT OF CSE, ATMECE, MYSURU Page 60

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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;
}

DEPT OF CSE, ATMECE, MYSURU Page 61

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

average waiting time = 2.75


average turn around time = 6.000
student@student:~/naveen$

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

average waiting time = 3.80


average turn around time = 7.000
student@student:~/naveen$

DEPT OF CSE, ATMECE, MYSURU Page 62

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

average waiting time = 3.60


average turnaround time = 7.200
student@student:~/naveen$

DEPT OF CSE, ATMECE, MYSURU Page 63

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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];

DEPT OF CSE, ATMECE, MYSURU Page 64

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

average waiting time = 2.75


average turn around time= 6.00

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

DEPT OF CSE, ATMECE, MYSURU Page 65

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

average waiting time = 3.6


average turn around time =7.20

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

average waiting time = 4.0


average turn around time 7.17

DEPT OF CSE, ATMECE, MYSURU Page 66

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software and Operating System Laboratory 18CSL66

Program Outcome :

• To implement Round robin


• To implement shortes remaining job first

Viva Questions:

• What is bottom up Parsing?

The Parsing method is which the Parse tree is constructed from the input language
string beginning from the leaves and going up to the root node.Bottom-Up parsing is
also called shift-reduce parsing due to its implementation. The YACC supports shift-
reduce parsing.
• What is the need of Operator precedence?
The shift reduce Parsing has a basic limitation. Grammars which can represent a left-
sentential parse tree as well as right-sentential parse tree cannot be handled by shift
reduce parsing. Such a grammar ought to

DEPT OF CSE, ATMECE, MYSURU Page 67

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

• 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
deciding whether 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 exist or not. But here we will
determine the total number of safe sequences and print all safe sequences.

/* Banker’s Program in C*/


#include<stdio.h>
#include<stdlib.h>
struct file
{
int all[10];
int max[10];
int need[10];
int flag;
};
void main()
{
struct file f[10];0
int fl;
int i,j,k,p,b,n,r,g,cnt=0,id,newr;
int avail[10],seq[10];
printf("enter the number of processess\n");
scanf("%d",&n);
printf("enter the number of resources\n");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("enter the details of p %d\n",i);

DEPT OF CSE, ATMECE, MYSURU Page 68

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 69

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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");
}
}

DEPT OF CSE, ATMECE, MYSURU Page 70

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

enter avialable resuruces


332
enter new request details
enter new pid
0
enter request for resuruces
110

p 1 is visited(422)
p 3 is visited(633)

DEPT OF CSE, ATMECE, MYSURU Page 71

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software and Operating System Laboratory 18CSL66
p 4 is visited(635)
p 0 is visited(755)
p 2 is visited(1057)

system is in safe state


safe sequence is P1 P3 P4 P0 P2

process allocation max need


P0 1 2 0 7 5 3 6 3 3
P1 2 0 0 3 2 2 1 2 2
P2 3 0 2 9 0 2 6 0 0
P3 2 1 1 2 2 2 0 1 1
P4 0 0 2 4 3 3 4 3 1

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

DEPT OF CSE, ATMECE, MYSURU Page 72

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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)

system is in safe state


safe sequence is P0 P2 P3 P4 P1

process allocation max need


P0 0 1 2 2 0 0 1 2 0 0 0 0
P1 1 0 0 0 1 7 5 6 0 7 5 6
P2 1 3 5 4 2 3 5 6 1 0 0 2
P3 0 6 3 2 0 6 5 2 0 0 2 0
P4 0 0 1 4 0 6 5 6 0 6 4 2

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

DEPT OF CSE, ATMECE, MYSURU Page 73

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

request is not granted Dead lock occured


system is in un safe state

process alocation max need


P0 3 2 1 4 3 7 1 1 6
P1 1 1 2 2 1 4 1 0 2
P2 1 0 3 1 3 3 0 3 0
P3 2 0 0 5 4 1 3 4 1

DEPT OF CSE, ATMECE, MYSURU Page 74

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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;

DEPT OF CSE, ATMECE, MYSURU Page 75

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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 process p"+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++)

DEPT OF CSE, ATMECE, MYSURU Page 76

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 77

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 78

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 79

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 80

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 81

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 82

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 83

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 84

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

• To implement bankers algorithms


• To find the safe sequence

Viva Questions

• What is exit status command?


Exit 0- return success, command executed successfully. Exit 1 – return failure.

• 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 communicate with
each other.

DEPT OF CSE, ATMECE, MYSURU Page 85

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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:

• To understand the paging concepts


• To implement LRU and FIFO
• To understand page replacement algorithms

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.

DEPT OF CSE, ATMECE, MYSURU Page 86

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

• Unlike FIFO, LRU does not suffer from Belady’s Anomaly.


• It gives less number of page faults than any other algorithm other than optimal and as optimal
algorithm cannot be implemented in real-life LRU is the most frequently used algorithm.
• LRU algorithm is very efficient.
Disadvantages 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.

/* LRU Program in C*/


#include<stdio.h>
int findLRU(int time[], int n)
{
int i, minimum = time[0], pos = 0;
for(i = 1; i < n; ++i)
{
if(time[i] < minimum)
{
minimum = time[i];
pos = i;
}
}
return pos;
}

int main()
{

DEPT OF CSE, ATMECE, MYSURU Page 87

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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)
{

DEPT OF CSE, ATMECE, MYSURU Page 88

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

Total Page Faults = 5


student@student:~/naveen$

Output2
student@student:~/naveen$ cc program9lru.c
student@student:~/naveen$ ./a.out

Enter number of frames: 4


Enter number of pages: 10
Enter reference string: 0 1 7 2 3 2 7 1 0 3

0 -1 -1 -1
0 1 -1 -1
0 1 7 -1
0 1 7 2

DEPT OF CSE, ATMECE, MYSURU Page 89

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

Total Page Faults = 7


student@student:~/naveen$

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

Total Page Faults = 10

DEPT OF CSE, ATMECE, MYSURU Page 90

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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;

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


{
if(time[i] < minimum)
{
minimum = time[i];
pos = i;
}
}

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);

System.out.println("Enter number of frames: ");


no_of_frames = sn.nextInt();
System.out.println("Enter number of pages: ");
no_of_pages=sn.nextInt();
System.out.println("Enter reference string: ");

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


{
pages[i]=sn.nextInt();
}
for(i = 0; i < no_of_frames; ++i)
{
frames[i] = -1;
}
for(i = 0; i < no_of_pages; ++i)
{

DEPT OF CSE, ATMECE, MYSURU Page 91

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software and Operating System Laboratory 18CSL66
flag1 = flag2 = 0;

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


{
if(frames[j] == pages[i])// checking for hit condition whether number is
already present in frame
{
counter++;
time[j] = counter; //1,2,3
flag1 = flag2 = 1; // flag1=1 means there is hit
break;
}
}
if(flag1 == 0) // there is no hit
{
for(j = 0; j < no_of_frames; ++j)
{
if(frames[j] == -1)
{
counter++;
faults++; // no of page faults
frames[j] = pages[i];// inserting page numbers into frames
time[j] = counter;
flag2 = 1; // flag1=1 means there is page fault
break;
}
}
}
if(flag2 == 0) // there is no hit
{
pos = findLRU(time, no_of_frames);// pos of frame where page number is to
be inserted
counter++;
faults++;
frames[pos] = pages[i]; // inserting page numbers into frames
time[pos] = counter;
}

System.out.println("\n");

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


{
System.out.print(frames[j]+"\t");
}

DEPT OF CSE, ATMECE, MYSURU Page 92

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 93

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

DEPT OF CSE, ATMECE, MYSURU Page 94

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software and Operating System Laboratory 18CSL66
2 0 1
Total Page Faults =12

DEPT OF CSE, ATMECE, MYSURU Page 95

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

DEPT OF CSE, ATMECE, MYSURU Page 96

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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 run in
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.

DEPT OF CSE, ATMECE, MYSURU Page 97

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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;
}

DEPT OF CSE, ATMECE, MYSURU Page 98

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software and Operating System Laboratory 18CSL66
Output1
student@student:~/naveen$ cc program9fifo.c
student@student:~/naveen$ ./a.out

ENTER THE NUMBER OF PAGES:


6

ENTER THE PAGE NUMBER :


130356

ENTER THE NUMBER OF FRAMES :3


ref string page frames
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
student@student:~/naveen$

Output2
student@student:~/naveen$ cc program9fifo.c
student@student:~/naveen$ ./a.out

ENTER THE NUMBER OF PAGES:


10

ENTER THE PAGE NUMBER :


0172327103

ENTER THE NUMBER OF FRAMES :4


ref string page frames
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

DEPT OF CSE, ATMECE, MYSURU Page 99

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

ENTER THE NUMBER OF PAGES:


12

ENTER THE PAGE NUMBER:


432143543215

ENTER THE NUMBER OF FRAMES: 3


ref string page frames
4 4 -1 -1
3 4 3 -1
2 4 3 2
1 1 3 2
4 1 4 2
3 1 4 3
5 5 4 3
4
3
2 5 2 3
1 5 2 1
5
Page Fault Is 9
student@student:~/naveen

DEPT OF CSE, ATMECE, MYSURU Page 100

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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");

DEPT OF CSE, ATMECE, MYSURU Page 101

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software and Operating System Laboratory 18CSL66
}
System.out.println("Page Fault Is "+count);

}
}

Output 1
ENTER THE NUMBER OF PAGES
6

ENTER THE PAGE NUMBER :


130356

ENTER THE NUMBER OF FRAMES :


3

ref string page frames

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

ENTER THE PAGE NUMBER :


432143543215

ENTER THE NUMBER OF FRAMES :


3
ref string page frames

4 4 -1 -1
3 4 3 -1
2 4 3 2
1 1 3 2
4 1 4 2
3 1 4 3

DEPT OF CSE, ATMECE, MYSURU Page 102

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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

ENTER THE PAGE NUMBER:


0172327103

ENTER THE NUMBER OF FRAMES :


4

ref string page frames

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

ENTER THE PAGE NUMBER :


701203042303120

ENTER THE NUMBER OF FRAMES :


3

DEPT OF CSE, ATMECE, MYSURU Page 103

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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:

• Give a small example to trace LRU


• Give a small example to trace FIFO

DEPT OF CSE, ATMECE, MYSURU Page 104

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

3. Explain lex and yacc tools


Lex: - scanner that can identify those tokens

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.

6. What is the Syntax of a Language?


The Rules which tells whether a string is a valid Program or not are called the Syntax.

7. What is the Semantics of a Language?


The Rules which gives meaning to programs are called the Semantics of a Language.

8. What are tokens?


When a string representing a program is broken into sequence of substrings, such that each
substring represents a constant, identifier, operator, keyword etc of the language, these
substrings are called the tokens of the Language.

9. What is the Lexical Analysis?


The Function of a lexical Analyzer is to read the input stream representing the Source program,
one character at a time and to translate it into valid tokens.

10. How can we represent a token in a language?


The Tokens in a Language are represented by a set of Regular Expressions. A regular
expression specifies a set of strings to be matched. It contains text characters and operator
characters. The Advantage of using regular expression is that a recognizer can be automatically
generated.

11. How are the tokens recognized?


The tokens which are represented by an Regular Expressions are recognized in an input string
by means of a state transition Diagram and Finite Automata.

DEPT OF CSE, ATMECE, MYSURU Page 105

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

13. How do we write the Regular Expressions?


The following are the most general notations used for expressing a R.E.

Symbol Description
| OR (alternation)
() Group of
Subexpression
* 0 or more
Occurrences
? 0 or 1 Occurrence
+ 1 or more
Occurrences
{n,m} n- m Occurrences

14. What are the Advantages of using Context-Free grammars?


• It is precise and easy to understand.
• It is easier to determine syntatic ambiguities and conflicts in the grammar.

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.

17. What are Terminals and non-Terminals in a grammar?


Terminals:- All the basic symbols or tokens of which the language is composed of are called
Terminals. In a Parse Tree the Leafs represents the Terminal Symbol.

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.

DEPT OF CSE, ATMECE, MYSURU Page 106

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
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.

19. What is bottom up Parsing?


The Parsing method is which the Parse tree is constructed from the input language string
beginning from the leaves and going up to the root node. Bottom-Up parsing is also called
shift- reduce parsing due to its implementation. The YACC supports shift-reduce parsing.

20. What is the need of Operator precedence?


The shift reduce Parsing has a basic limitation. Grammars which can represent a left-
sentential parse tree as well as right-sentential parse tree cannot be handled by shift reduce
parsing. Such a grammar ought to have two non-terminals in the production rule. So the
Terminal sandwiched between these two non-terminals must have some associability and
precedence. This will help the parser to understand which non-terminal would be expanded
first.

21. What is an internal command? Give an example?


Command which is shell built- in eg:echo

22. What is an external command? Give a example?


Command which resides in other directories-eg:cd in /bin

23. What are shell scripts?


Using a program, we can run more than one command.

24. What is exit status command?


Exit 0- return success, command executed successfully.
Exit 1 – return failure.

25. Difference between fork() and vfork().


• The only way a new process is created by the Unix kernel is when an existing process
calls the fork function. The new process created by fork is called the child processThis
function is called once but returns twice. The only difference in the return valuein the child
is 0 while the return value in the parent is the process ID of the new child.

• 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.

26. Difference between wait() and waitpid()


• wait can block the caller until a child process terminates, while waitpid has an option that
prevents it from blocking.
• waitpid doesn‘t wait for the first child to terminate, it has a number of options that control
which process it waits for.

27. Define API‘s


An application programming interface (API) is a source code based specification intended to

DEPT OF CSE, ATMECE, MYSURU Page 107

Download & Share VTU Connect App Now From Google Play Store
Download & Share VTU Connect App Now From Google Play Store
System Software and Operating System Laboratory 18CSL66
be used as an interface by software components to communicate with each other.

28. Define Race Condition.


Race condition occurs when multiple processes are trying to do something with shared data
and the final outcome depends on the order in which the processes run.

DEPT OF CSE, ATMECE, MYSURU Page 108

Download & Share VTU Connect App Now From Google Play Store

You might also like