18CSL66 - SS Lab Manual

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

Bapuji Education Association ®

Bapuji Institute of Engineering and Technology, Davangere.

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING (ACADEMIC YEAR 2020-21)

LABORATORY MANUAL

SUBJECT: SYSTEM SOFTWARE LABORATORY

SUBJECT CODE: 18CSL66

SEMESTER: VI

2018 CBCS Scheme


INSTITUTIONAL MISSION AND VISION

Vision

"To be a center of excellence recognized nationally and internationally, in distinctive areas


of engineering education and research, based on a culture of innovation and invention"

Mission

"BIET contributes to the growth and development of its students by imparting a broad based
engineering education and empowering them to be successful in their chosen field by inculcating in
them positive approach, leadership qualities and ethical values"

Department of Computer Science & Engineering


Vision of the Department

"To be a center-of-excellence by imbibing state-of-the-art technology in the field of Computer


Science and Engineering, thereby enabling students to excel professionally and be ethical" Mission
of the Department
M Adapting best teaching and learning techniques that cultivates Questioning and Reasoning
1 culture among the students.

M2 Creating collaborative learning environment that ignites the critical thinking in students
and leading to the innovation.

M3 Establishing Industry Institute relationship to bridge the skill gap and make them industry
ready and relevant.

M4 Mentoring students to be socially responsible by inculcating ethical and moral values.

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.
∙ 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: Analyze and develop solutions for problems that are complex in nature but
applying the knowledge acquired from the core subjects of this program.. 2. PSO2:
To develop secure, Scalable, Resilient and distributed applications for industry and
societal requirements.
3. PSO3: To learn and apply the concepts and construct of emerging technologies like
Artificial Intelligence, Machine learning, Deep learning, Big Data Analytics, IOT,
Cloud Computing, etc for any real time problems.

Program Educational Objectives (PEOs):

PEO1: To apply skills acquired in the discipline of Computer Science and Engineering for
PEO2:
solving societal and industrial problems with apt technology intervention To continue
their career in industry/academia or to pursue higher studies and research. PEO3: To become
successful entrepreneurs, innovators to design and develop software products and services that
meet the societal, technical and business challenges.

PEO4: To work in the diversified environment by acquiring leadership qualities with


effective communication skills accompanied by professional and ethical
values.
SYSTEM SOFTWARE LABORATORY
[As per Choice Based Credit System (CBCS)scheme]
(Effective from the academic year 2018 -2019)
SEMESTER – VI

Subject Code 18CSL66 CIE Marks 40

Number of Contact Hours/Week 0:2:2 SEE Marks 60

Total Number of Lab Contact Hours 36 Exam Hours 03 Hrs


CREDITS – 02

Course objectives: This course will enable students to


∙ To make students familiar with Lexical Analysis and Syntax Analysis phases of
Compiler Design and implement programs on these phases using LEX & YACC
tools and/or C/C++/Java
∙ To enable students to learn different types of CPU scheduling algorithms used in
operating system.
∙ To make students able to implement memory management - page replacement and
deadlock handling algorithms

Description (If any):


Exercises to be prepared with minimum three files (Where ever necessary):
1. Header file.
2. Implementation file.
3. Application file where main function will be present.
The idea behind using three files is to differentiate between the developer and user sides. In the
developer side, all the three files could be made visible. For the user side only header file and
application files could be made visible, which means that the object code of the
implementation file could be given to the user along with the interface given in the header file,
hiding the source file, if required. Avoid I/O operations (printf/scanf) and use data input file
where ever it is possible.

Lab Experiments:
1.
a) Write a LEX program to recognize valid arithmetic expression. Identifiers in
the expression could be only integers and operators could be + and *. Count
the identifiers & operators present and print them separately.

b) Write YACC program to evaluate arithmetic expression involving


operators:+, -, *, and /

2. Develop, Implement and Execute a program using YACC tool to recognize


n
all strings ending with b preceded by n a’s using the grammar a 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.
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

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 : 20
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
& 22
operators present and print them separately.
b)Write YACC program to evaluate arithmetic
expression involving operators: +, -, *, and /

7. Program 2 : Develop, Implement and Execute a program using 25


YACC tool to recognize all strings ending with b preceded by n a’s
using the grammar an b (note: input n value)

8. Program 3: Design, develop and implement YACC/C program to 28


construct Predictive / LL(1) Parsing Table for the grammar rules:
A →aBa , B →bB | ε. Use this table to parse the
sentence: abba$

9. Program 4: Design, develop and implement YACC/C program to 33


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.

10. Program 5: Design, develop and implement a C/Java program 40


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
11. Program 6 : 43
a) Write a LEX program to eliminate comment lines in a
C program and copy the resulting program into a separate 46
file.
b)Write YACC program to recognize valid identifier,
operators and keywords in the given text (C program) file.

12. Program 7: Design, develop and implement a C/C++/Java program to 50


simulate the working of Shortest remaining time and Round Robin
(RR) scheduling algorithms. Experiment with different quantum sizes
for RR algorithm

13. Program 8: Design, develop and implement a C/C++/Java program 68


toimplement Banker’s algorithm. Assume suitable input required
todemonstrate the results

14. Program 9: Design, develop and implement a C/C++/Java program 86


to implement page replacement algorithms LRU and FIFO. Assume
suitable input required to demonstrate the results.

15. Viva Questions and Answers 105

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:


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

nd
2 Step: lex program1.l
rd
3 Step: cc lex.yy.c –ll
th
4 Step: ./a.out

Structure of LEX source program:


Copied to the beginning of C code
routine called yylex()
Code Section
Definition
Section

Rule Section Lex specification is translated Lex.yy.c code


into a file containing a C

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

Page 1
System Software Laboratory 18CSL66
Note: If the scanner is part of a parser developed using Yacc, only steps 1 and 2 should be
performed. Read the part B on Yacc.

Now let's look at the kind of program format that Lex understands. A Lex program is divided into
three sections:

∙ The first section has global C and Lex declarations (regular expressions). ∙
The second section has the patterns (coded in C)

∙ The third section has supplemental C functions. main(), for example,


These sections are delimited by %%.
Let us consider a word counting lex program to understand the sections in

detail. 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*/ }

%%

Page 2
System Software Laboratory 18CSL66 C code:

The third and final section of programming in Lex covers C function declarations (and
occasionally the main function)

Note that this section has to include the yywrap() function. Lex has a set of functions and variables
that are available to the user.

One of them is yywrap. Typically, yywrap() is defined as shown in the example below.
void main()

{
yylex(); /* start the analysis*/

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 ofstatistics.
∙ -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

Page 3
System Software Laboratory 18CSL66 Lex functions
yylex() The function that starts the analysis. It is automatically generated by Lex.

yywrap() This function is called when end of file (or input) is encountered. If this
function returns 1, the parsing stops. So, this can be used to parse
multiple files. Code can be written in the third section, which will allow
multiple files to be parsed. The strategy is to make yyin file pointer (see
the preceding table) point to a different file until all the files are parsed.
At the end, yywrap() can return 1 to indicate end of parsing.

yyless(int This function can be used to push back all but first characters of the
) read token.

yymore() This function tells the lexer to append the next token to the current token.
Regular Expressions

It is used to describe the pattern. It is widely used to in lex. It uses meta language. The character
used in this Meta language is part of the standard ASCII character set.

An expression is made up of symbols.Normal symbols are characters and numbers, but there are
other symbols that have special meaning in Lex. The following two tables define some of the
symbols used in Lex and give a few typical examples
Character Meaning

A-Z, 0-9, a-z Characters and numbers that form part of the pattern.

. Matches any character except \n.

- Used to denote range. Example: A- Z implies all characters from A

[] A character class. Matches any character in the brackets. If the


first character is ^ then it indicates a negation pattern. Example:
[abC] matches either of a, b, and C.

* Match zero or more occurrences of the preceding pattern.

+ Matches one or more occurrences of the preceding pattern.(no


empty string)Ex: [0-9]+ matches ―1‖,‖111‖ or ―123456‖ but not an
empty string.

? Matches zero or one occurrences of the preceding pattern. Ex:


-?[0-9]+ matches a signed number including an optional leading

? Matches zero or one occurrences of the preceding pattern. Ex:


-?[0-9]+ matches a signed number including an optional leading

$ Matches end of line as the last character of the pattern.

{} 1) Indicates how many times a pattern can be present.


Example: A{1,3} implies
one to three occurrences of A may be present.
2) If they contain name, they refer to a substitution by that name.
Ex:

\ Used to escape meta characters. Also used to remove the


special meaning of characters as defined in this table.
Ex: \n is a newline character, while ―\*‖ is a literal asterisk.

Page 4
System Software Laboratory 18CSL66
^ Negation.

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


Page 5
System Software Laboratory 18CSL66
CHAPTER 2
Introduction to YACC
YACC provides a general tool for imposing structure on the input to a computer program. The
input specification is a collection of grammar rules. Each rule describes an allowable structure and
gives it a name. YACC prepares a specification of the input process. YACC generates a function to
control the input process. This function is called a parser.

The name is an acronym for ―Yet Another Compiler. YACC generates the code for the parser in
the C programming language. YACC was developed at AT& T for the UNIX operating system.
YACC has also been rewritten for other languages, including JAVA, ADA

The function parser calls the lexical analyzer to pick up the tokens from the input stream. These
tokens are organized according to the input structure rules .The input structure rule is called as
grammar. When one of the rule is recognized, then user code supplied for this rule (user code is
action) is invoked. Actions have the ability to return values and makes use of the values ofother
actions.

Steps
in writing YACC Program:

st
1 step: Using gedit editor create a file with extension y.
For example: program1.y
nd
2 Step: yacc –d program1.y
rd
3 Step: lex program1.l
th Step
4 : cc y.tab.c lex.yy.c -ll

th Step
5 : /a.out

Page 6
System Software Laboratory 18CSL66 When we run YACC, it generates a parser in file y.tab.c
and also creates an include file y.tab.h. To obtain tokens, YACC calls yylex. Function yylex has a
return type of int and returns the token. Values associated with the token are returned by lex in
variable yylval.

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

Page 7
System Software Laboratory 18CSL66
Rule Section

The rules section simply consists of a list of grammar rules. A grammar rule has the form:

A: BODY

A represents a nonterminal name, the colon and the semicolon are YACC punctuation and
BODY represents names and literals. The names used in the body of a grammar rule may
represent tokens or nonterminal symbols. The literal consists of a character enclosed in
single quotes.

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.
Page 8
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 e.g. cp old.file new.file
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 mv –i old.file/tmp


overwriting files)

Remove file(- intention) rm –i sam.txt

Compare two files and show differences diff

Page 9
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 diff


files.

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

script Make file record of al terminal activity

Page 10
System Software Laboratory 18CSL66
CHAPTER 4
Introduction to Operating System
An Operating System is a program that manages the Computer hardware. It controls and
coordinates the use of the hardware among the various application programs for the various users.
A Process is a program in execution. As a process executes, it changes state
∙ New : The process is being created
∙ Running : Instructions are beingexecuted
∙ Waiting : The process is waiting for some event to occur
∙ Ready : The process is waiting to be assigned to a process
∙ Terminated : The process has finished execution

Apart from the program code, it includes the current activity represented by
∙ ProgramCounter
∙ Contents of Processor registers,
∙ Process Stack which contains temporary data like functions parameters,
return addresses and local variables

∙ Data section which contains global variables


∙ Heap for dynamic memory allocation

A Multi-programmed system can have many processes running simultaneously with the CPU
multiplexed among them. By switching the CPU between the processes, the OS can make the
computer more productive. There is Process Scheduler which selects the process among many
processes that are ready, for program execution on the CPU. Switching the CPU to another process
Scheduling Algorithms
CPU Scheduler can select processes from ready queue based on various scheduling algorithms.
Different scheduling algorithms have different properties, and the choice of a particular algorithm
may favor one class of processes over another. The scheduling criteria include
∙ CPU utilization:
∙ Throughput: The number of processes that are completed per unit time.
∙ Waiting time: The sum of periods spent waiting in readyqueue.
∙ Turnaround time: The interval between the time of submission of process to the
time of completion.
∙ Response time: The time from submission of a request until the first response
is produced.

Page 11
System Software Laboratory 18CSL66
The different scheduling algorithms are

∙ FCFS: First Come First Served Scheduling


∙ SJF: Shortest Job First Scheduling
∙ SRTF: Shortest Remaining Time First Scheduling
∙ PriorityScheduling
∙ 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 selectsprocess
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.

Page 12
System Software Laboratory 18CSL66
∙ It is practically infeasible as Operating System may not know burst time and therefore may
not sort them. While it is not possible to predict execution time, several methods can be
used to estimate the execution time for a job, such as a weighted average of previous
execution times. SJF can be used in specialized environments where accurate estimates of
running time are available

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

Page 13
System Software Laboratory 18CSL66
Banker’s Algorithm in Operating System
∙ Banker’s Algorithm is a resource allocation and deadlock avoidance algorithm. This algorithm
test for safety simulating the allocation for predetermined maximum possible amounts of all
resources, then makes an “s-state” check to test for possible activities, before decidingwhether
allocation should be allowed to continue.
∙ In simple terms, it checks if allocation of any resource will lead to deadlock or not, OR is it
safe to allocate a resource to a process and if not then resource is not allocated to that process.
Determining a safe sequence (even if there is only 1) will assure that system will not go into
deadlock.
∙ Banker’s algorithm is generally used to find if a safe sequence exists or not. But here we will
determine the total number of safe sequences and print all safe sequences.
Page 14
System Software Laboratory 18CSL66
CHAPTER 5
Sample Lex and Yacc Programs
Examples of sample Lex Program and Yacc Programs

Sample Program 1

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++;
%%

Page 15
System Software Laboratory 18CSL66
main()
{
yylex();
printf("num of words %d\n",wc);
}

Output
student@student:~/naveen$ lex sample.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
BIET Colllege of Engineering
num of words 4

Sample Program 3

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
BIET 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;
%}

Page 16
System Software Laboratory 18CSL66
%option noyywrap
%%
"/*"[^"*/"]*"*/" countcomment++;
"//".* countcomment++;
%%
main()
{
printf("enter comment lines\n");
yylex();
printf("No of Comments %d\n",countcomment);
}

Output
student@student:~/naveen$ lex countcomments.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out
enter comment lines
// BIET College of Engineering

/* */

// this is ss os lab

/* Welcome* /

No of Comments 4
student@student:~/naveen$

Sample Program 5

Aim: Program to count the number of characters, words, spaces and lines in a given input
file.

%{
#include<stdio.h>
int wc,cc,lc,sc;
%}
word[^ \t\n]+
line[\n]
space[ ]
%%
{word} {wc++;cc+=yyleng;}
{line} {lc++;cc++;}
{space} {sc++;cc++;}
%%
int main(int argc,char * argv[])
{
if(argc!=2)
{

Page 17
System Software Laboratory 18CSL66
printf("\n\t Usage:./a.out filename\n");
return 0;
}
yyin=fopen(argv[1],"r");
yylex();
printf("\n Number of lines=%d",lc);
printf("\n Number of words=%d",wc);
printf("\n Number of character=%d",cc);
printf("\n Number of spaces=%d\n",sc);
return 0;
}

Output1
student@student:~/naveen$ lex countlswc.l
student@student:~/naveen$ cc lex.yy.c -ll
student@student:~/naveen$ cat a.txt
BIET college of engineering
student@student:~/naveen$ ./a.out a.txt
Number of lines=1
Number of words=4
Number of character=28
Number of spaces=3
student@student:~/naveen$

Output2
student@student:~/naveen$ lex countlswc.l
student@student:~/naveen$ cc lex.yy.c -ll
student@student:~/naveen$ cat b.txt
BIET college of
engineering
student@student:~/naveen$ ./a.out b.txt
Number of lines=2
Number of
Words=4Number of
character=26 Number of
spaces=3
student@student:~/naveen$

Sample Program 6

Aim:Program to recognize a valid variable, which starts with a letter, followed by any
number of letters or digits.

Lex part
%{
#include"y.tab.h"
%}
%option noyywrap
%%
[a-zA-Z]+ return l;
[0-9]+ return d;
[\t] ;

Page 18
System Software Laboratory 18CSL66
\n return 0;
. return yytext[0];
%%
Yacc part
%{
#include<stdio.h>
%}
%token l d
%%
var:l s {printf("valid variable");return 0;}
s:s l
|s d
|;
%%

main()
{
printf("enter the variable");
yyparse();
}
yyerror()
{
printf("invalid variable");
exit(0);
}

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

Page 19
System Software Laboratory 18CSL66
Program No.1a: Write a LEX program to recognize valid arithmetic
expression. Identifiers in the expression could be only integers and operators
could be + and *. Count the identifiers & operators present and print them
separately.

Program Objective :

∙ 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");
}

Page 20
System Software Laboratory 18CSL66
Output 1
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out enter
arthimetic expression
(1+2)
1+2
valid expression
No of Identifers=2
No of operators=1

Output 2
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out enter
arthimetic expression
((1+2)*3)
1+2*3
valid expression
No of Identifers=3
No of operators=2

Output 3
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out enter
arthimetic expression
((1+2)
1+2
invalid expression

Output 4
student@student:~/naveen$ lex program1.l
student@student:~/naveen$ cc lex.yy.c
student@student:~/naveen$ ./a.out enter
arthimetic expression
((1+2)*3
1+2*3
invalid expression
Page 21
System Software Laboratory 18CSL66
Program No.1b: Write YACC program to evaluate arithmetic expression
involving operators: +, -, *, and /.
lex part

%{
#include "y.tab.h"
extern int yylval;
%}
%%
[0-9]+ {yylval=atoi(yytext);return num;}
[\+\-\*\/] {return yytext[0];}
[)] {return yytext[0];}
[(] {return yytext[0];}
. {;}
\n {return 0;}
%%

yacc part
%{
#include<stdio.h>
#include<stdlib.h>
int yyerror();
int yylex();
%}
%token num
%left '+''-'
%left '*''/'
%%
input:exp{printf("%d\n",$$);exit(0);}
exp:exp'+'exp{$$=$1+$3;}
|exp'-'exp{$$=$1-$3;}
|exp'*'exp{$$=$1*$3;}
|exp'/'exp {if($3==0){printf("Divide by Zero\n");exit(0);} else
$$=$1/$3;}
|'('exp')'{$$=$2;}
|num{$$=$1;};
%%
int yyerror()
{
printf("error");
exit(0);
}

Page 22
System Software Laboratory 18CSL66
int main()
{
printf("enter expression\n");
yyparse();
}
Output1
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
(2+4)*(2-8)
-36
student@student:~/naveen$

Output2
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
5/0
Divide by Zero

Output3
student@student:~/naveen$ yacc -d program1b.y
student@student:~/naveen$ lex program1b.l
student@student:~/naveen$ cc y.tab.c lex.yy.c -ll
student@student:~/naveen$ ./a.out
enter expression
(2*5)/5
2
Page 23
System Software Laboratory 18CSL66

Program Outcome

∙ 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.
Page 24
System Software Laboratory 18CSL66
Program No. 2: Develop, Implement and execute a program using YACC tool
to recognize all strings ending with b preceded by n a’s using the grammar a n
b (note: input n value).
Program Objective :

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

Page 25
System Software Laboratory 18CSL66
else
yyerror();
return 0;
}
int yyerror()
{
printf("invalid string\n");
exit(0);
}
Output1
student@student-OptiPlex-390:~$ yacc -d program2.y
student@student-OptiPlex-390:~$ lex program2.l
student@student-OptiPlex-390:~$ cc y.tab.c lex.yy.c -ll
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
ab
valid string

Output2
student@student-OptiPlex-390:~$ ./a.out
enter value for n
2
enter input string with a's and b's
aab
valid string

Output3
student@student-OptiPlex-390:~$ ./a.out
enter value for n
0
enter input string with a's and b's
b
valid string

Output4
student@student-OptiPlex-390:~$ ./a.out
enter value for n
0
enter input string with a's and b's
ab
invalid string

Page 26
System Software Laboratory 18CSL66
Output5
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
aab
invalid string

Output6
student@student-OptiPlex-390:~$ ./a.out
enter value for n
1
enter input string with a's and b's
acb
invalid string
student@student-OptiPlex-390:~$
Program Outcome:

∙ 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

Page 27
System Software Laboratory 18CSL66
Program No. 3: Design, develop and implement YACC/C program to construct
Predictive / LL (1) Parsing Table for the grammar rules: A →aBa , B →bB | ε.
Use this table to parse the sentence: abba$.
Program Objective :

∙ 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]);
}

Page 28
System Software Laboratory 18CSL66

int numr(char c)
{
switch(c)
{
case 'A': return 1;
case 'B': return 2;
case 'a': return 1;
case 'b': return 2;
case '@': return 3;
}
return(1);
}
void calulatefollow()
{
char str1[20]="A->aBa",str2[20]="B->bB",str3[20]="B->@";
int n1=6,n2=5,n3=4,i,j,k;
printf("\nFOLLOW SET \n");
printf("\n FOLLOW(A)=$\n");
for(i=3;i<n1;i++)
{
if(str1[i]=='B')
printf("FOLLOW(B)=%c",str1[5]);
newstr[0]=str1[5];
}
}

void main()
{
char c;
int i,j,k,n,n1=6;
char str1[20]="A->aBa",str2[20]="B->bB",str3[20]="B->@";
for(i=0;i<3;i++)
for(j=0;j<4;j++)
strcpy(table[i][j],"e");
printf("\n Grammar:\n");
for(i=0;i<3;i++)
printf("%s\n",prod[i]);
printf("\nfirst(A)= {%s}\n",first[0]);
printf("\nfirst(B)= {%s,%s}\n",first[1],first[2]);
calulatefollow();
strcpy(table[0][0]," ");
strcpy(table[0][1],"a");

Page 29
System Software Laboratory 18CSL66
strcpy(table[0][2],"b");
strcpy(table[0][3],"$");
strcpy(table[1][0],"A");
strcpy(table[2][0],"B");
for(i=0;i<3;i++)
{
k=strlen(first[i]);
for(j=0;j<k;j++)
if(first[i][j]!='@')
strcpy(table[numr(prod[i][0])][numr(first[i][j])],prod[i])
; else
strcpy(table[numr(prod[i][0])][numr(follow[i][j])],prod[i]);
}
printf("\n \n");
printf("\n LL(1) PARSER TABLE \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%s\t",table[i][j]);
}
printf("\n");
}
printf("\n");
printf("\n \n");
printf("enter the input string terminated with $ to parse :- ");
scanf("%s",input);
for(i=0;input[i]!='\0';i++)
if((input[i]!='a')&&(input[i]!='b')&&(input[i]!='$'
)) {
printf("invalid string");
exit(0);
}
if(input[i-1]!='$')
{
printf("\n\nInput String Entered Without End marker $");
exit(0);
}
push('$');
push('A');
i=0;
printf("\n\n");
printf(" stack\t Input \taction ");
printf("\n - \n");

Page 30
System Software Laboratory 18CSL66
while(input[i]!='$' && stack[top]!='$')
{
display();
printf("\t\t%s\t ",(input+i));
if (stack[top]==input[i])
{
printf("\tmatched %c\n",input[i]);
pop();
i++;
}
else
{
if(stack[top]>=65 && stack[top]<92)
{
strcpy(curp,table[numr(stack[top])][numr(input[i])]
); if(!(strcmp(curp,"e")))
{
printf("\n invalid string- Rejected\n");
exit(0);
}
else
{
printf(" \tapply production %s\n",curp);
if(curp[3]=='@')
pop();
else
{
pop();
n=strlen(curp);
for(j=n-1;j>=3;j--)
push(curp[j]);

}
}
}

}
display();
printf("\t\t%s\t ",(input+i));
printf("\n \n"); if(stack[top]=='$' && input[i]=='$' )
{

Page 31
System Software Laboratory 18CSL66
printf("\n valid string - Accepted\n");

}
else
{
printf("\ninvalid string- Rejected\n");
}
}
Output
student@student-OptiPlex-390:~$ cc program3.c
student@student-OptiPlex-390:~$ ./a.out
Grammar:
A->aBa
B->bB
B->@

first(A)= {a}

first(B)= {b,@}

FOLLOW SET
FOLLOW(A)=$
FOLLOW(B)=a

LL(1) PARSER TABLE


ab
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$ $ matched a
a$ $ -
valid string – Accepted
student@student-OptiPlex-390:~$

Page 32
System Software Laboratory 18CSL66 Program No.4: Design, develop and
implement YACC/C program to demonstrate Shift Reduce Parsing technique for
the grammar rules: E →E+T | T, T →T*F | F, F → (E) | id and parse the
sentence: id + id * id.

Program Objective:

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

Page 33
System Software Laboratory 18CSL66
Top-down Parsing

When the parser starts constructing the parse tree from the start symbol and then tries to
transform the start symbol to the input, it is called top-down parsing.

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.

Page 34
System Software Laboratory 18CSL66
#include<stdio.h>
#include<string.h>
int k=0,z=0,i=0,j=0,c=0;
char a[16],ac[20],stk[15],act[10];
void check();
int main()
{
printf("GRAMMAR is:\n E->E+T|T \nT->T*F|F\nF->(E)|id\n");
printf("Enter input string\n");
gets(a);
c=strlen(a);
printf("stack \t input \t action\n");
printf("------\t ------\t ------\n");
printf("\n$%s\t%s$\t",stk,a);
for(k=0,i=0; j<c; k++,i++,j++)
{
if(a[j]=='i' && a[j+1]=='d')
{
strcpy(act,"SHIFT ");
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='\0';
a[j]=' ';
a[j+1]=' ';
printf("\n$%s\t%s$\t%sid",stk,a,act);
check();
}
else if(a[j]=='+'||a[j]=='*')
{
strcpy(act,"SHIFT ");
stk[i]=a[j];
stk[i+1]='\0';
a[j]=' ';
printf("\n$%s\t%s$\t%s%c",stk,a,act,stk[i]);
check();
}
else
{
printf("\nERROR IN INPUT\n");
break;
}
}
if(stk[0]=='E' && j==c)
printf("\n****SUCCESSFULL PARSING****\n");

Page 35
System Software Laboratory 18CSL66
else
printf("\n****FAILURE IN PARSING****\n");
}
void check()
{
strcpy(ac,"REDUCE F->id");
for(z=0; z<c; z++)
if(stk[z]=='i' && stk[z+1]=='d')
{
stk[z]='F';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
j++;
}
strcpy(ac,"REDUCE T->T*F");
for(z=0; z<c; z++)
if(stk[z]=='T' && stk[z+1]=='*' && stk[z+2]=='F')
{
stk[z]='T';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
strcpy(ac,"REDUCE T->F");
for(z=0; z<c; z++)
if(stk[z]=='F' )
{
stk[z]='T';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
}
strcpy(ac,"REDUCE E->E+T");
for(z=0; z<c; z++)
{
if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='T' && stk[z+3]!='*' && a[j+1]!='*')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
stk[z+3]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}

Page 36
System Software Laboratory 18CSL66
else if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='T' && j==c)
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
else
break;
}
strcpy(ac,"REDUCE E->T");
for(z=0; z<c; z++)
if(stk[z]=='T' )
{
if(a[j+1]=='+'||a[j+1]=='\0')
{
stk[z]='E';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
}
else
break;
}
strcpy(ac,"REDUCE F->(E)");
for(z=0; z<c; z++)
if(stk[z]=='(' && stk[z+1]=='E' && stk[z+2]==')')
{
stk[z]='F';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;
}
}

Page 37
System Software Laboratory 18CSL66
Output
student@localhost:~/naveen$ cc program4.c
student@localhost:~/naveen$ ./a.out
GRAMMAR is:
E->E+T|T
T->T*F|F
F->(E)|id
Enter input string
id+id*id
stack input action
--
$ id+id*id$
$id +id*id$ SHIFT id $F +id*id$ REDUCE
F->id $T +id*id$ REDUCE T->F $E
+id*id$ REDUCE E->T $E+ id*id$ SHIFT
+ $E+id *id$ SHIFT id $E+F *id$
REDUCE F->id $E+T *id$ REDUCE T->F
$E+T* id$ SHIFT * $E+T*id $ SHIFT id
$E+T*F $ REDUCE F->id $E+T $
REDUCE T->T*F $E $ REDUCE E->E+T
****SUCCESSFULL PARSING****

student@localhost:~/naveen$

Page 38
System Software Laboratory 18CSL66

Program Outcome :

∙ 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 inputstream 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 containstext


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

Page 39
System Software Laboratory 18CSL66
Program No.5: Design, develop and implement a C/Java program to generate
the machine code using Triples for the statement A = -B * (C +D) whose
intermediate code in three-address form:
T1 = -B
T2 = C + D
T3 = T1 * T2
A = T3
Program Objective :

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

Page 40
System Software Laboratory 18CSL66
if(strcmp(op,"/")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nDIV R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
if(strcmp(op,"=")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nMOV %s,R0",result);
}
}
fclose(fp1);
fclose(fp2);
}

Output
input.txt
T1 -B =?
T2 C + D
T3 T1 * T2
A T3 =?

student@localhost:~/naveen$ cc program5.c
student@localhost:~/naveen$ ./a.out
student@localhost:~/naveen$ cat output.txt
MOV R0,-B
MOV T1,R0
MOV R0,C
ADD R0,D
MOV T2,R0
MOV R0,T1
MUL R0,T2
MOV T3,R0
MOV R0,T3
MOV A,R0
MOV R0,T3
MOV A,R0

Page 41
System Software Laboratory 18CSL66

Program Outcome
∙ 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 regularexpression,
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.

Page 42
System Software Laboratory 18CSL66
Program No. 6a: Write a LEX program to eliminate comment lines in a C
program and copy the resulting program into a separate file.
Program Objective:

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

Page 43
System Software Laboratory 18CSL66
Output1
student@student:~$ lex program6.l
student@student:~$ cc lex.yy.c
student@student:~$ cat >a.c
#include<stdio.h>
main()
{
int a,b,c;
/* declaration */
printf("------------");
scanf(" -------- ");
// for reading
getch();
}

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
}

Page 44
System Software Laboratory 18CSL66
student@student:~$ ./a.out a1.c b1.c
number of comment lines 4
student@student:~$ cat b1.c main()
{
int a,b,c;
printf("--------------");
scanf(" -------- ") ;
getch();
}
student@student:~$

Page 45
System Software Laboratory 18CSL66
Program No. 6b: WriteYACC program to recognize valid identifier, operators
and keywords in the given text (C program) file.
lex part
%{
#include <stdio.h>
#include "y.tab.h"
extern yylval;
%}
%%
[ \t] ;
[+|-|*|/|=|<|>] {printf("operator is %s\n",yytext);return OP;}
[0-9]+ {yylval = atoi(yytext); printf("numbers is %d\n",yylval); return DIGIT;}
int|char|bool|float|void|for|do|while|if|else|return|void {printf("keyword
is%s\n",yytext);return KEY;}
[a-zA-Z0-9]+ {printf("identifier is %s\n",yytext);return ID;}
.;
%%

yacc part
%{
#include <stdio.h>
#include <stdlib.h>
int yyerror();
int yylex();
int id=0, dig=0, key=0, op=0;
%}
%token DIGIT ID KEY OP
%%
input:
DIGIT input {dig++;}
| ID input {id++;}
| KEY input { key++; }
| OP input {op++;}
| DIGIT { dig++;}
| ID { id++;}
| KEY {key++;}
| OP {op++;}
;
%%
Page 46
System Software Laboratory 18CSL66
#include <stdio.h>
extern int yylex();
extern int yyparse();
extern FILE *yyin;
main()
{
FILE *myfile = fopen("input.c", "r");
if (!myfile)
{
printf("I can't open input.c!");
return -1;
}
yyin = myfile;
do
{
yyparse();
}
while (!feof(yyin));
printf("Number of numbers = %d\n Number ofKeywords = %d\n Number of
Identifiers = %d\n Number of noperators = %d\n",dig, key,id, op); }
int yyerror()
{
printf("error");
exit(0);
}

Output
input.c
void main()
{
int a;
float b;
char c;
char d;
int sum=40;
if(sum>=40)
printf("---pass--");
else
printf("---fail--");
}

Page 47
System Software Laboratory 18CSL66
student@localhost:~/naveen$ yacc -d program6b.y
student@localhost:~/naveen$ lex program6b.l
student@localhost:~/naveen$ cc y.tab.c lex.yy.c -ll
student@localhost:~/naveen$ ./a.out
keyword is void
identifier is main

keyword is int
identifier is a

keyword is float
identifier is b

keyword is char
identifier is c

keyword is char
identifier is d

keyword is int
identifier is sum
operator is =
numbers is 40

keyword is if
identifier is sum
operator is >
operator is =
numbers is 40

identifier is printf
identifier is pass

keyword is else

identifier is printf
identifier is fail
Number of numbers = 2
Number of Keywords = 8
Number of Identifiers = 11
Number of n operators = 3
student@localhost:~/naveen$

Page 48
System Software Laboratory 18CSL66

Program Outcome :

∙ 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.
Page 49
System Software Laboratory 18CSL66
Program No. 7: Design, develop and implement a C/C++/Java program to
simulate the working of shortest remaining time and Round Robin (RR)
scheduling algorithms. Experiment with different quantum sizes for RR
algorithm.

Program Objective:

∙ 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

Page 50
System Software Laboratory 18CSL66
Graphical Representation of Round Robin Algorithm

Page 51
System Software Laboratory 18CSL66
/* Round Robin Program in C*/

#include<stdio.h>
int main()
{
int i,j,n,time,x,counter=0,time_quantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
x=n;
for(i=0;i<n;i++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",i+1);
scanf("%d",&at[i]);
scanf("%d",&bt[i]);
rt[i]=bt[i];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,i=0;x!=0;)
{
if(rt[i]<=time_quantum && rt[i]>0)
{
time+=rt[i];
rt[i]=0;
counter=1;
}
else if(rt[i]>0)
{
rt[i]-=time_quantum;
time+=time_quantum;
}
if(rt[i]==0 && counter==1)
{
x--;
printf("P[%d]\t|\t%d\t|\t%d\n",i+1,time-at[i],time-at[i]-bt[i]);
wait_time+=time-at[i]-bt[i];
turnaround_time+=time-at[i];
counter=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
Page 52
System Software Laboratory 18CSL66
i++;
else
i=0;
}
printf("\nAverage Waiting Time= %.2f\n",wait_time*1.0/n);
printf("Average Turnaround Time = %.2f",turnaround_time*1.0/n);

return 0;
}

Output1
student@student:~/naveen$ cc program7rr.c
student@student:~/naveen$ ./a.out
Enter Total Process: 3
Enter Arrival Time and Burst Time for Process Process Number 1 :0 7
Enter Arrival Time and Burst Time for Process Process Number 2 :2 4
Enter Arrival Time and Burst Time for Process Process Number 3 :4 1
Enter Time Quantum: 3

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

Page 53
System Software Laboratory 18CSL66
Average Waiting Time= 9.25
Average Turnaround Time = 14.75
student@student:~/naveen$

Output3
student@student:~/naveen$ cc program7rr.c
student@student:~/naveen$ ./a.out
Enter Total Process: 5
Enter Arrival Time and Burst Time for Process Process Number 1 :0 8
Enter Arrival Time and Burst Time for Process Process Number 2 :1 1
Enter Arrival Time and Burst Time for Process Process Number 3 :2 3
Enter Arrival Time and Burst Time for Process Process Number 4 :3 2
Enter Arrival Time and Burst Time for Process Process Number 5 :4 6
Enter Time Quantum: 3

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$
Page 54
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;
}

Page 55
System Software Laboratory 18CSL66
if(rt[i]==0 && counter==1)
{
x--;
System.out.print("process"+i+"\t");
System.out.print(time-at[i]+"\t");
System.out.print("\t");
System.out.print(time-at[i]-bt[i]);
System.out.println("\t");
wait_time+=time-at[i]-bt[i];
turnaround_time+=time-at[i];
counter=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
i++;
else
i=0;
}
System.out.println("\n Average Waiting Time="+wait_time*1.0/n);
System.out.println("Average Turnaround Time ="+turnaround_time*1.0/n);
}
}
Output 1
Enter Total Process:
3
Enter Arrival Time for Process
0
Enter burst time of process 0
7
Enter Arrival Time for Process
2
Enter burst time of process 1
4
Enter Arrival Time for Process
4
Enter burst time of process 2
1
Enter Time Quantum:
3

Page 56
System Software Laboratory 18CSL66
Process |Turnaround Time |Waiting Time Process 2 3 2
Process 1 9 5 Process 0 12 5

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

Page 57
System Software Laboratory 18CSL66
Output3
Enter Total Process:
5
Enter Arrival Time for Process
0
Enter burst time of process 0
6
Enter Arrival Time for Process
0
Enter burst time of process 1
5
Enter Arrival Time for Process
0
Enter burst time of process 2
2
Enter Arrival Time for Process
0
Enter burst time of process 3
3
Enter Arrival Time for Process
0
Enter burst time of process 4
7
Enter Time Quantum:
2

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

Page 58
System Software Laboratory 18CSL66
1
Enter burst time of process 1
5
Enter Arrival Time for Process
2
Enter burst time of process 2
2
Enter Arrival Time for Process
3
Enter burst time of process 3
1
Enter Arrival Time for Process
4
Enter burst time of process 4
6
Enter Arrival Time for Process
6
Enter burst time of process 5
3
Enter Time Quantum:
2

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

Page 59
System Software Laboratory 18CSL66
Shortest Remaining Time First (SRTF) Scheduling Algorithm
∙ The Preemptive version of Shortest Job First(SJF) scheduling is known as Shortest Remaining
Time First (SRTF). With the help of the SRTF algorithm, the process having the smallest
amount of time remaining until completion is selected first to execute. So basically in SRTF,
the processes are scheduled according to the shortest remaining time.
∙ However, the SRTF algorithm involves more overheads than the Shortest job first
(SJF)scheduling, because in SRTF OS is required frequently in order to monitor the
CPU time of the jobs in the READY queue and to perform context switching.

∙ In the SRTF scheduling algorithm, the execution of any process can be stopped after a
certain amount of time. On arrival of every process, the short-term scheduler schedules
those processes from the list of available processes & running processes that have the
least remaining burst time.

∙ After all the processes are available in the ready queue, then, No preemption will be done
and then the algorithm will work the same as SJF scheduling. In the Process Control
Block, the context of the process is saved, when the process is removed from the
execution and when the next process is scheduled. The PCB is accessed on the next
execution of this process

Advantages of SRTF
∙ The main advantage of the SRTF algorithm is that it makes the processing of the jobs
faster than the SJF algorithm, mentioned it’s overhead charges are not counted.

Disadvantages of SRTF
∙ In SRTF, the context switching is done a lot more times than in SJN due to more
consumption of the CPU's valuable time for processing. The consumed time of CPUthen
adds up to its processing time and which then diminishes the advantage of fast
processing of this algorithm.
Page 60
System Software Laboratory 18CSL66
/* Shortest Remaining Time Program in C*/
#include<stdio.h>
int n,qtum,pid[10],a[10],b[10],tt[10],avg[10];
int swt=0,stat=0;
float f_avg_turn_arnd_time=0.0,f_avg_wait_time=0.0;
int main()
{
int ch;
int a[10],b[10],x[10],i,smallest, count=0,time=0,n;
double avg=0,tt=0,end;
printf("enter the number of processes:\n");
scanf("%d",&n);
printf("enter arrival time\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the burst time \n");
for(i=0;i<n;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
x[i]=b[i];
b[9]=9999;
for(time=0;count!=n;time++)
{
smallest=9;
for(i=0;i<n;i++)
{
if(a[i]<=time && b[i]<b[smallest] && b[i]>0)
smallest=i;
}
b[smallest]--;
if(b[smallest]==0)
{
count++;
end=time+1;
avg=avg+end-a[smallest]-x[smallest];
tt=tt+end-a[smallest];
}
}
printf("\n average waiting time = %.2lf\n",avg/n);
printf("average turn around time = %.3lf",tt/n);
return 1;
}

Page 61
System Software Laboratory 18CSL66
Output 1
student@student:~/naveen$ cc program7srt.c
student@student:~/naveen$./a.out enter the
number of processes:
4
enter arrival time
0
1
2
4
enter the burst time
5
3
4
1

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$

Page 62
System Software and Operating System Laboratory 18CSL66
Output 3
student@student:~/naveen$ cc program7srt.c
student@student:~/naveen$./a.out
enter the number of processes:
5
enter arrival time
0
1
2
3
4
enter the burst time
8
4
2
1
3

average waiting time = 3.60


average turnaround time = 7.200
student@student:~/naveen$
Page 63
System Software and Operating System Laboratory 18CSL66
/*Shortest Remaining Time Program in Java */
import java.util.Scanner;
public class ShortestRemainingTime
{
public static void main(String[] args)
{
int i,n,smallest, count=0,time=0;
float avg=0,tt=0,end;
int[] a = new int[20];
int[] b = new int[20];
int[] x = new int[20];
int[] at = new int[20];
int[] pid = new int[20];
Scanner sn=new Scanner(System.in);
System.out.println("enter the number of processes:");
n=sn.nextInt();
for(i=0;i<n;i++)
{
System.out.println("Enter Arrival Time for Process :"+i);
a[i]=sn.nextInt();
}
for(i=0;i<n;i++)
{
System.out.println("Enter burst Time for Process :"+i);
b[i]=sn.nextInt();
}
for(i=0;i<n;i++)
x[i]=b[i];
b[9]=9999;
for(time=0;count!=n;time++)
{
smallest=9;
for(i=0;i<n;i++)
{
if(a[i]<=time && b[i]<b[smallest] && b[i]>0)
smallest=i;
} // end of for loop
b[smallest]--;
if(b[smallest]==0)
{
count++;
end=time+1;
avg=avg+end-a[smallest]-x[smallest];
tt=tt+end-a[smallest];

Page 64
System Software and Operating System Laboratory 18CSL66
}
}
// end of outer for loop
System.out.println("\n average waiting time = "+avg/n);
System.out.format("average turn around time= %.2f",tt/n);
}

Output1
enter the number of processes:
4
Enter Arrival Time for Process :0
0
Enter Arrival Time for Process :1
1
Enter Arrival Time for Process :2
2
Enter Arrival Time for Process :3
4
Enter burst Time for Process :0
5
Enter burst Time for Process :1
3
Enter burst Time for Process :2
4
Enter burst Time for Process :3
1

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

Page 65
System Software and Operating System Laboratory 18CSL66
Enter burst Time for Process :0 8
Enter burst Time for Process :1 4
Enter burst Time for Process :2 2
Enter burst Time for Process :3 1
Enter burst Time for Process :4 3

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

Page 66
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
Page 67
System Software and Operating System Laboratory 18CSL66
Program No. 8: Design, develop and implement a C/C++/Java program to
implement Banker’s algorithm. Assume suitable input required to demonstrate
the results.

Program Objective :

∙ To understand Deadlocks
∙ To understand the Bankers algorithm

Theory

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

Page 68
System Software and Operating System Laboratory 18CSL66
printf("enter the allocation\n");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("enter the max \n");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("enter avialable resuruces\n");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
printf("enter new request details\n");
printf("enter new pid \n");
scanf("%d",&id);
printf("enter request for resuruces\n");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i]+=newr;
avail[i]=avail[i]-newr;
}
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
else

Page 69
System Software and Operating System Laboratory 18CSL66
b=b-1;
}
if(b==r)
{
printf("\np%d is visited",j);
// put processes in to safe sequence array
seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<n;k++)
printf("%3d",avail[k]); // print new allocation resources
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("request is not granted Dead lock occured\n");
printf("system is in un safe state\n");
goto y;
}
}
printf("\n system is in safe state\n");
printf(" safe sequence is ");
for(i=0;i<fl;i++)
printf("P%d",seq[i]);
y:
printf("\n process \t allocation \t max \t need\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
printf(" %3d",f[i].all[j]);
for(j=0;j<r;j++)
printf(" %3d",f[i].max[j]);
for(j=0;j<r;j++)
printf(" %3d",f[i].need[j]);
printf("\n");
}
}

Page 70
System Software and Operating System Laboratory 18CSL66
Output1

student@student:~/naveen$ cc program8.c
student@student:~/naveen$ ./a.out enter
the number of processess
5
enter the number of resources
3
enter the details of p 0
enter the allocation
010
enter the max
753
enter the details of p 1
enter the allocation
200
enter the max
322
enter the details of p 2
enter the allocation
302
enter the max
902
enter the details of p 3
enter the allocation
211
enter the max
222
enter the details of p 4
enter the allocation
002
enter the max
433

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)

Page 71
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

Page 72

You might also like