0% found this document useful (0 votes)
38 views

17CSL67 Lab Manual

This document provides information about the System Software & Operating System Laboratory course for the 6th semester Bachelor of Engineering program in Computer Science & Engineering at AMC Engineering College in Bangalore. It includes the vision and mission statements of the institution and department, as well as the program educational objectives, program specific objectives, and program outcomes. It also outlines the course details, syllabus, and 8 programming assignments that students must complete for the laboratory course covering topics like Lex, Yacc, UNIX, operating systems, scheduling algorithms, and page replacement algorithms.

Uploaded by

Abcd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

17CSL67 Lab Manual

This document provides information about the System Software & Operating System Laboratory course for the 6th semester Bachelor of Engineering program in Computer Science & Engineering at AMC Engineering College in Bangalore. It includes the vision and mission statements of the institution and department, as well as the program educational objectives, program specific objectives, and program outcomes. It also outlines the course details, syllabus, and 8 programming assignments that students must complete for the laboratory course covering topics like Lex, Yacc, UNIX, operating systems, scheduling algorithms, and page replacement algorithms.

Uploaded by

Abcd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

AMC ENGINEERING COLLEGE,

BANGALORE

Department of Computer Science & Engineering

B.E VI Semester

SYSTEM SOFTWARE & OPERATING SYSTEM LABORATORY


(17CSL67)
CBCS SCHEME

Name: ………………….

USN: ………………….

VISVESVARAYA TECHNOLOGICAL UNIVERSITY


“Jnana Sangama”, BELAGAVI – 590 018
KARNATAKA
Table of Contents

Sl. No. Particulars. Page No.


1 Vision and Mission of Institution 1
2 Vision and Mission of Department 2
3 PEO, PSO, PO 3
4 Course Details 6
 Course Objectives
 Syllabus
 Course Outcomes

5 CHAPTER 1 Introduction to LEX 9


1.1 Steps in writing LEX Program 9
1.2 Structure of LEX source program 9
1.3 Regular Expressions 10
6 CHAPTER 2 Introduction to YACC 10
2.1 Steps in writing YACC Program 13
2.2 Structure of YACC source program 14
7 CHAPTER 3 Introduction to UNIX 16
8 CHAPTER 4 Introduction to Operating Systems 18
4.1 Scheduling Algorithms 19
4.2 Deadlocks 19
9 CHAPTER 5 Lab Syllabus Programs
Program 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 &
20
operators present and print them separately.
b. Write YACC program to evaluate arithmetic expression
involving operators: +, -, *, and /.
Program 2 Develop, Implement and execute a program using YACC tool
to recognize all strings ending with b preceded by n a’s using 23
the grammar a n b (note: input n value).
Program 3 Design, develop and implement YACC/C program to
construct Predictive / LL (1) Parsing Table for the grammar 24
rules: A →aBa, B →bB | ε. Use this table to parse the
sentence: abba$.
Program 4 Design, develop and implement YACC/C program to
demonstrate Shift Reduce Parsing technique for the grammar 30
rules: E →E+T | T, T →T*F | F, F →(E) | id and parse the
sentence: id + id * id.
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 34
T2 = C + D
T3 = T1 + T2
A = T3
Program 6 a. Write a LEX program to eliminate comment lines in a C
program and copy the resulting program into a separate file. 36
b. Write YACC program to recognize valid identifier,
operators and keywords in the given text (C program)
file.
Program 7 Design, develop and implement a C/C++/Java program to
simulate the working of Shortest remaining time and Round 40
Robin (RR) scheduling algorithms. Experiment with different
quantum sizes for RR algorithm.
Program 8 Design, develop and implement a C/C++/Java program to
implement Banker’s algorithm. Assume suitable input required 47
to demonstrate the results.
Program 9 Design, develop and implement a C/C++/Java program to
implement page replacement algorithms LRU and FIFO. 52
Assume suitable input required to demonstrate the results.
10 CHAPTER 6 Extra Programs 57
11 CHAPTER 7 Viva Questions 68
12 CHAPTER 8 Content Beyond Syllabus 71
1

Vision of the Institute

“To be a leader in imparting value based Technical Education


and Research for the benefit of society”.

Mission of the Institute


M1 To provide state of the art Infrastructure facilities
To implement modern pedagogical methods in
M2 delivering the academic programs with experienced
and committed faculties
To create a vibrant ambience that promotes Learning,
M3
Research, Invention and Innovations
To undertake manpower and skill development
M4
programmes for Academic Institutions and Industries
To enhance Institute Industry Interface through
M5
Collaborative Research and Consultancy
To generate and disseminate knowledge through
M6 training program workshops, seminars, conferences,
publications
To be a more comprehensive college in terms of the
M7
number of programs offered
To relentlessly pursue professional excellence with
M8
ethical and moral values

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


2

Department of
Computer Science and engineering

Vision of the Department


“To develop the department as a center of excellence in the area
of Information Science and Engineering for the benefit of
society”.
Mission of the Department

To provide the State-of-the-Art Infrastructure and Technology in


MD1
the field of Information Science and Engineering.
To deliver value based education through modern teaching
MD2
pedagogy.
To impart theoretical, computational and practical knowledge in
MD3
the area of Information Technology.
To collaborate with Institute, Industry and Research Organizations
MD4
for the Cutting Edge Technologies.
To develop an Entrepreneurial, Ethical and Socially responsible
MD5
professionals.

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


3

Program Educational Objectives


Graduates possess advanced knowledge of Computer Science &
PEO 1
Engineering and excel in leadership roles to serve the society
Graduates of the program will apply Computer Engineering tools
PEO 2 in core technologies for improving knowledge in the
Interdisciplinary Research and/or Entrepreneurs
Graduates adapt Value-Based Proficiency in solving real time
PEO 3
problems.

Program Specific Objectives


Professional Skills: Ability of using mathematical methodologies for
analysis of computing concepts, data structure, computer hardware,
layered technologies and suitable algorithm which in turn helps
PSO 1 graduates to model, design and implement a system to meet specific
requirement

Software Skills: Ability to build Software Engineering System for


PSO 2 lifecycle development by using analytical knowledge in Computer
Science & Engineering and applying modern methodologies

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


4

Program Outcomes (POs)


Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,


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

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

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

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

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

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

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

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


5

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.

9. Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

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

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

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

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


6

Course Details
Course Name : System Software and Compiler Design / Operating Systems Lab
Course Code : 15CSL67
Course prerequisite : Basic Knowledge on Lex, YACC, C programming, UNIX
commands and shell scripts

Course Objectives

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

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


7

Syllabus
Subject Code : 17CSL67 IA Marks :20
No. of Practical Hrs/ Week: 01I + 02P Exam Hours: 03
Total No. of Practical Hrs.: 40 Exam Marks: 60

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

Laboratory 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 a n 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

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


Global 8

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.
10. a) Design, develop and implement a C/C++/Java program to simulate a numerical calculator
b) Design, develop and implement a C/C++/Java program to simulate page replacement technique
Note: In Examination, for question No 10: Students may be asked to execute any one of the above (10(a)
or 10(b)- Examiner choice)

Course Outcomes
Upon successful completion of this course, students are able to:

15CSL67
System Software & Compiler Design / Operating Systems Lab
COs COURSE OUTCOMES

CO1 Implement and demonstrate Lexer’s and Parser’s

CO2 Evaluate different algorithms required for management, scheduling,


allocation and communication used in operating system.

Conduction of Practical Examination:



All laboratory experiments are to be included for practical examination.

Students are allowed to pick one experiment from the lot.

Strictly follow the instructions as printed on the cover page of answer script

Marks distribution: Procedure + Conduction + Viva:20 + 50 +10 (80)

Change of experiment is allowed only once and marks allotted to the procedure part to be
made zero

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


9

1. Introduction to LEX

Lex and YACC helps you write programs that transforms structured input. Lex generates C
code for lexical analyzer whereas 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.

1.1 Steps in writing LEX Program:

1st step: Using gedit create a file with extension l. For example: prg1.l
2nd Step: lex prg1.l
3rd Step: cc lex.yy.c –ll
4th Step: ./a.out

1.2 Structure of LEX source program:

1stCol 2ndCol 3rdCol 4thCol


DEFINITION SECTION
%%
RULE SECTION
%%
CODE SECTION

% 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

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


10

Lex variables

yyin Of the type FILE*. This points to the current file being parsed by the lexer.
yyout Of the type FILE*. This points to the location where the output of the lexer will be
written. By default, both yyin and yyout point to standard input and output.
yytext The text of the matched pattern is stored in this variable (char*).
yyleng Gives the length of the matched pattern.
yylineno Provides current line number information. (May or may not be supported by the
lexer.)

Lex functions

yylex() The function that starts the analysis. It is automatically generated by Lex.
yywrap() This function is called when end of file (or input) is encountered. If this function
returns 1, the parsing stops. So, this can be used to parse multiple files. Code can
be written in the third section, which will allow multiple files to be parsed. The
strategy is to make yyin file pointer (see the preceding table) point to a different
file until all the files are parsed. At the end, yywrap() can return 1 to indicate end
of parsing.
yyless(int n) This function can be used to push back all but first ‘n’ characters of the read token.
yymore() This function tells the lexer to append the next token to the current token.

1.3 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 are 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 to Z.
[] A character class. Matches any character in the brackets. If the first character is
^ then it indicates a negation pattern. Example: [abC] matches either of a, b,
and C.

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


11

Character Meaning
* Match zero or more occurrences of the preceding pattern.
+ Matches one or more occurrences of the preceding pattern.(no empty string)
Ex: [0-9]+ matches “1”,”111” or “123456” but not an empty string.
? Matches zero or one occurrences of the preceding pattern.
Ex: -?[0-9]+ matches a signed number including an optional leading minus.
? Matches zero or one occurrences of the preceding pattern.
Ex: -?[0-9]+ matches a signed number including an optional leading minus.
$ Matches end of line as the last character of the pattern.
{} 1) Indicates how many times a pattern can be present. Example: A{1,3} implies
one to three occurrences of A may be present.
2) If they contain name, they refer to a substitution by that name.
Ex: {digit}
\ Used to escape meta characters. Also used to remove the special meaning of
characters as defined in this table.
Ex: \n is a newline character, while “\*” is a literal asterisk.
^ Negation.
| Matches either the preceding regular expression or the following regular
expression. Ex: cow|sheep|pig matches any of the three words.
"< symbols>" Literal meanings of characters. Meta characters hold.
/ Look ahead. Matches the preceding pattern only if followed by the succeeding
expression. Example: A0/1 matches A0 only if A01 is the input.
() Groups a series of regular expressions together into a new regular expression.
Ex: (01) represents the character sequence 01. Parentheses are useful when
building up complex patterns with *,+ and |

Examples of regular expressions

Regular 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 from b to e.
[0-9] 0 or 1 or 2 or………9
[0-9]+ 1 or 111 or 12345 or …At least one occurrence of preceding 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

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


12

Examples of token declarations

Token Associated expression Meaning


number ([0-9])+ 1 or more occurrences of a digit
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 System Software & Operating Systems Lab – 17CSL67


13

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 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 of
other actions.

2.1 Steps in writing YACC Program:

1st step: Usinggedit editor create a file with extension y. For example: prg1.y
2nd Step: YACC –d prg1.y
3rd Step: lex prg1.l
4th Step: cc y.tab.c lex.yy.c -ll
5th Step: /a.out

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.

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


14

2.2 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 System Software & Operating Systems Lab – 17CSL67


15

Rules 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 System Software & Operating Systems Lab – 17CSL67


16

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 directories ls -R *.*
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.filenew.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 overwriting mv –i old.file/tmp
files)
Remove file(-intention) rm –i sam.txt
Compare two files and show differences diff

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


17

File Utilities

Action UNIX options & filespec


View a file vi file.txt
Concatenate files cat file1file2 to standard output.
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 System Software & Operating Systems Lab – 17CSL67


18

4. Introduction to Operating Systems


Introduction

An Operating System is a program that manages the Computer hardware. It controls and coordinates the
use of the hardware among the various application programs for the various users.

A Process is a program in execution. As a process executes, it changes state


New : The process is being created

Running: Instructions are being executed

Waiting: The process is waiting for some event to occur

Ready : The process is waiting to be assigned to a process


 Terminated : The process has finished execution

Apart from the program code, it includes the current activity represented by

Program Counter,
 Contents of Processor registers,

Process Stack which contains temporary data like function parameters, return addresses and local
variables

Data section which contains global variables
 Heap for dynamic memory allocation

A Multi-programmed system can have many processes running simultaneously with the CPU
multiplexed among them. By switching the CPU between the processes, the OS can make the computer
more productive. There is Process Scheduler which selects the process among many processes that are
ready, for program execution on the CPU. Switching the CPU to another process requires performing a
state save of the current process and a state restore of new process, this is Context Switch.

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


19

4.1 Scheduling Algorithms

CPU Scheduler can select processes from ready queue based on various scheduling algorithms. Different
scheduling algorithms have different properties, and the choice of a particular algorithm may favor one
class of processes over another. The scheduling criteria include

CPU utilization:

Throughput: The number of processes that are completed per unit time.

Waiting time: The sum of periods spent waiting in ready queue.

Turnaround time: The interval between the time of submission of process to the time of
completion.

Response time: The time from submission of a request until the first response is produced.

The different scheduling algorithms are



FCFS: First Come First Served Scheduling

SJF: Shortest Job First Scheduling

SRTF: Shortest Remaining Time First Scheduling

Priority Scheduling

Round Robin Scheduling

Multilevel Queue Scheduling

Multilevel Feedback Queue Scheduling

4.2 Deadlocks

A process requests resources; and if the resource is not available at that time, the process enters a waiting
state. Sometimes, a waiting process is never able to change state, because the resource is has requested is
held by another process which is also waiting. This situation is called Deadlock. Deadlock is
characterized by four necessary conditions

Mutual Exclusion

Hold and Wait

No Preemption

Circular Wait

Deadlock can be handled in one of these ways,



Deadlock Avoidance

Deadlock Detection and Recover

Dept. of CSE System Software & Operating System Lab – 17CSL67


20

5. Lab Syllabus Programs

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

%{
#include<stdio.h>
int v=0,op=0,id=0,flag=0;
%}
%%
[a-zA-Z]+[0-9A-Za-z]* {id++;printf("\n Identifier:");ECHO;}
[\+\-\*\/\=] {op++;printf("\n Operartor:");ECHO;}
"(" {v++;}
")" {v--;}
";" {flag=1;}
.|\n {;}
%%
main()
{
printf("Enter the expression"); yylex();
if((op+1) ==id && v==0 && flag==0)
printf("\n Expression is Valid\n"); else
printf("\n Expression is Invalid\n");
}
Execution Steps:
Lex <lexfilename.l>
cc lex.yy.c –ll
. /a.out <temp.txt>

Output:

Dept. of CSE System Software & Operating System Lab – 17CSL67


b. Write YACC program to evaluate arithmetic expression involving operators: +, -, *, and /
Lex Part / YACC Part

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

%{
#include<stdio.h> #include<stdlib.h>
%}
%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);
}
int main()
{
printf("Enter an expression:\n");

yyparse();
}

Dept. of CSE System Software & Operating System Lab – 17CSL67


2. Develop, Implement and execute a program using YACC tool to recognize all strings ending with

b preceded by n a’s using the grammar a n b (note: input n value).

Lex Part
%{
#include "y.tab.h"
%}
%%
a {return A;}
b {return B;}
[\n] return '\n';
%%

YACC Part
%{
#include<stdio.h>
#include<stdlib.h>
%}
%token A B
%%
input:s'\n' {printf("Successful Grammar\n");exit(0);} s: A s1
B| B
s1: ; | A s1
%%
main()
{
printf("Enter A String\n");
yyparse();
}

int yyerror()
{
printf("Error \n");
exit(0);
}
Output:

Dept. of CSE System Software & Operating System Lab – 17CSL67


24

3. Design, develop and implement YACC/C program to construct Predictive / LL(1) Parsing Table
for the grammar rules: A →aBa , B →bB | ε. Use this table to parse the sentence: abba$.
#include<stdio.h>
#include<conio.h>
#include<string.h> void
main()
{
char fin[10][20],st[10][20],ft[20][20],fol[20][20];
int a=0,e,i,t,b,c,n,k,l=0,j,s,m,p; printf("enter the no.
of coordinates\n"); scanf("%d",&n);

printf("enter the productions in a grammar\n"); for(i=0;i<n;i++)


scanf("%s",st[i]);
for(i=0;i<n;i++)
fol[i][0]='\0';
for(s=0;s<n;s++)
{
for(i=0;i<n;i++)
{
j=3;
l=0;
a=0;
l1:if(!((st[i][j]>64)&&(st[i][j]<91)))
{
for(m=0;m<l;m++)
{
if(ft[i][m]==st[i][j])
goto s1;
}
ft[i][l]=st[i][j];
l=l+1; s1:j=j+1;
}
else
{
if(s>0)
{
while(st[i][j]!=st[a][0])
{
a++;
}
b=0;

Dept. of CSE System Software & Operating System Lab – 17CSL67


25

while(ft[a][b]!='\0')
{
for(m=0;m<l;m++)
{
if(ft[i][m]==ft[a][b])
goto s2;
}
ft[i][l]=ft[a][b];
l=l+1; s2:b=b+1;
}
}
}
while(st[i][j]!='\0')
{
if(st[i][j]=='|')
{
j=j+1;
goto l1;
}
j=j+1;
}
ft[i][l]='\0';
}
}
printf("first pos\n");
for(i=0;i<n;i++)
printf("FIRS[%c]=%s\n",st[i][0],ft[i]);
fol[0][0]='$';
for(i=0;i<n;i++)
{
k=0;
j=3;
if(i==0)
l=1;
else
l=0;
k1:while((st[i][0]!=st[k][j])&&(k<n))
{
if(st[k][j]=='\0')
{
k++;
j=2;

Dept. of CSE System Software & Operating System Lab – 17CSL67


26

}
j++;
}
j=j+1;
if(st[i][0]==st[k][j-1])
{
if((st[k][j]!='|')&&(st[k][j]!='\0'))
{
a=0;
if(!((st[k][j]>64)&&(st[k][j]<91)))
{
for(m=0;m<l;m++)
{
if(fol[i][m]==st[k][j])
goto q3;
}
q3:
fol[i][l]=st[k][j];
i++;
}
else
{
while(st[k][j]!=st[a][0])
{
a++;
}
p=0;
while(ft[a][p]!='\0')

{
if(ft[a][p]!='@')
{
for(m=0;m<l;m++)
{
if(fol[i][m]==ft[a][p])
goto q2;
}
fol[i][l]=ft[a][p];
l=l+1;
}
else e=1;
q2:p++;

Dept. of CSE System Software & Operating System Lab – 17CSL67


29
27

}
if(e==1)
{
e=0;
goto a1;
}
}
}
else
{
a1:c=0;
a=0;
while(st[k][0]!=st[a][0])
{
a++;

}
while((fol[a][c]!='\0')&&(st[a][0]!=st[i][0]))
{
for(m=0;m<l;m++)
{
if(fol[i][m]==fol[a][c])
goto q1;
}
fol[i][l]=fol[a][c];
l++;
q1:c++;
}
}
goto k1;
}
fol[i][l]='\0';
}
printf("follow pos\n");
for(i=0;i<n;i++)
printf("FOLLOW[%c]=%s\n",st[i][0],fol[i]);
printf("\n");
s=0;
for(i=0;i<n;i++)
{
j=3;

Dept. of CSE System Software & Operating System Lab – 17CSL67


30
28
while(st[i][j]!='\0')
{
if((st[i][j-1]=='|')||(j==3))
{
for(p=0;p<=2;p++)
{
fin[s][p]=st[i][p];
}
t=j; for(p=3;((st[i][j]!='|')&&(st[i][j]!='\0'));p++)
{
fin[s][p]=st[i][j];
j++;
}
fin[s][p]='\0';
if(st[i][t]=='@')
{
b=0;
a=0;
while(st[a][0]!=st[i][0])
{
a++;
}
while(fol[a][b]!='\0')
{
printf("M[%c,%c]=%s\n",st[i][0],fol[a][b],fin[s]); b++;
}
}
else if(!((st[i][t]>64)&&(st[i][t]<91)))
printf("M[%c,%c]=%s\n",st[i][0],st[i][t],fin[s]); else
{
b=0;

a=0;
while(st[a][0]!=st[i][3])
{
a++;
}
while(ft[a][b]!='\0')
{
printf("M[%c,%c]=%s\n",st[i][0],ft[a][b],fin[s]); b++;
}
}
s++;
Dept. of CSE System Software & Operating System Lab – 17CSL67
31
30

}
if(st[i][j]=='|')
j++;
}
}
getch();
}
Output:

Dept. of CSE System Software & Operating System Lab – 17CSL67


32

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

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 System Software & Operating System Lab – 17CSL67


33
#include<stdio.h>
#include<conio.h>
#include<string.h>
int k=0,z=0,i=0,j=0,c=0;
char a[16],ac[20],stk[15],act[10];
void check();
void main()
{
puts("GRAMMAR is E->E+E \n E->E*E \n E->(E) \n E->id"); puts("enter input
string ");
gets(a);
c=strlen(a);
strcpy(act,"SHIFT->"); puts("stack
\t input \t action"); for(k=0,i=0; j<c;
k++,i++,j++)
{
if(a[j]=='i' && a[j+1]=='d')
{
stk[i]=a[j];
stk[i+1]=a[j+1];
stk[i+2]='\0';
a[j]=' ';
a[j+1] =' ';
printf("\n$%s\t%s$\t%sid”, stk,a,act); check();
}
else

Dept. of CSE System Software & Operating System Lab – 17CSL67


34
{
stk[i]=a[j];
stk[i+1]='\0';
a[j]=' ';
printf("\n$%s\t%s$\t%ssymbols",stk,a,act); check();
}
}
getch();
}
void check()
{
strcpy(ac,"REDUCE TO E");
for(z=0; z<c; z++)
if(stk[z]=='i' && stk[z+1]=='d')
{
stk[z]='E';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac); j++;
}
for(z=0; z<c; z++)
if(stk[z]=='E' && stk[z+1]=='+' && stk[z+2]=='E')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+2]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac); i=i-2;
}
for(z=0; z<c; z++)
if(stk[z]=='E' && stk[z+1]=='*' && stk[z+2]=='E')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac); i=i-2;
}
for(z=0; z<c; z++)
if(stk[z]=='(' && stk[z+1]=='E' && stk[z+2]==')')
{
stk[z]='E';
stk[z+1]='\0';
stk[z+1]='\0';
printf("\n$%s\t%s$\t%s",stk,a,ac);
i=i-2;}}

Dept. of CSE System Software & Operating System Lab – 17CSL67


35

5. Design, develop and implement a C/Java program to generate the machine code using Triples for the
statement A = -B * (C +D) whose intermediate code in three-address form:
T1 = -B
T2 = C + D
T3 = T1 *
T2 A = T3
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
char op[2],arg1[5],arg2[5],result[5];
void main()
{
FILE *fp1,*fp2;
fp1=fopen("input.txt","r");
fp2=fopen("output.txt","w");

while(!feof(fp1))
{

fscanf(fp1,"%s%s%s%s",result,arg1,op,arg2);
if(strcmp(op,"+")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nADD R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);

}
if(strcmp(op,"*")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);

fprintf(fp2,"\nMUL R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
if(strcmp(op,"-")==0)
{
fprintf(fp2,"\nMOV R0,%s",arg1);
fprintf(fp2,"\nSUB R0,%s",arg2);
fprintf(fp2,"\nMOV %s,R0",result);
}
if(strcmp(op,"/")==0)

Dept. of CSE System Software & Operating Systems Lab – 17CSL67


35

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);
getch();
}
Output:

input.txt output.txt
T1 -B = ? MOV R0,-B
T2 C + D MOV T1,R0
T3 T1 * T2 MOV R0,C
A T3 = ? ADD R0,D
MOV T2,R0
MOV R0,T1
MUL R0,T2
MOV T3,R0
MOV R0,T3
MOV A,R0

Dept. of CSE System Software & Operating System Lab – 15CSL67


36

6. a) Write a LEX program to eliminate comment lines in a C program and copy the resulting
program into a separate file.
%{
#include<stdio.h>
int c_count=0; %}

%%
"/*"[^*/]*"*/" {c_count++;} /*for single and multiple line comments*/
"//".* {c_count++;} /*for single line comments*/

%%
int main( int argc, char **argv)
{
FILE *f1,*f2;
if(argc>1) /*Pass two filenames for execution*/
{
f1=fopen(argv[1],"r"); /*open first file for reading*/
if(!f1) /*not able to open file*/
{
printf("file error \n");
exit(1);
}
yyin=f1;
f2=fopen(argv[2],"w"); /*open second file for writing*/
if(!f2) /*not able to open file*/
{
printf("Error");
exit(1);
}
yyout=f2;

yylex();
printf("Number of Comment Lines: %d\n",c_count);
}
return 0;
}

Dept. of CSE System Software & Operating System Lab – 17CSL67


37

b) Write YACC program to recognize valid identifier, operators and keywords in the given text (C
program) file.
Lex File
%{
#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 File
%{
#include <stdio.h>
#include <stdlib.h>
int id=0, dig=0, key=0, op=0;
%}
%token DIGIT ID KEY OP
%%
input:
DIGIT input { dig++; }
| ID input { id++; }
| KEY input { key++; }
| OP input {op++;}
| DIGIT { dig++; }
| ID { id++; }
| KEY { key++; }
| OP { op++;}
;
%%
#include <stdio.h>
extern int yylex();
extern int yyparse();
extern FILE *yyin;
main() {

Dept. of CSE System Software & Operating System Lab – 17CSL67


39
FILE *myfile = fopen("sam_input.c", "r"); if (!myfile) {
printf("I can't open sam_input.c!");
return -1;
}
yyin = myfile;
do { yyparse();
} while (!feof(yyin));
printf("numbers = %d\nKeywords = %d\nIdentifiers = %d\noperators = %d\n", dig, key,id,
op);
}
void yyerror() {
printf("EEK, parse error! Message: ");
exit(-1);
}
Output :

Dept. of CSE System Software & Operating System Lab – 17CSL67


40

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.
Round-robin (RR) is one of the algorithms employed by process and network schedulers in
computing. As the term is generally used, time slices (also known as time quanta) are assigned to each
process in equal portions and in circular order, handling all processes without priority (also known as
cyclic executive). Round-robin scheduling is simple, easy to implement, and starvation-free. Round-robin
scheduling can also be applied to other scheduling problems, such as data packet scheduling in computer
networks. It is an operating system concept.

The name of the algorithm comes from the round-robin principle known from other fields, where each
person takes an equal share of something in turn.
#include<stdio.h> struct
proc
{
int id;
int arrival;
int burst; int
rem; int
wait; int
finish;
int turnaround;
float ratio;
}process[10]; //structure to hold the process information struct
proc temp;
int no;

int chkprocess(int);
int nextprocess();
void roundrobin(int, int, int[], int[]); void
srtf(int);
main()
{
for(; ;)
{
int n,tq,choice;
int bt[10],st[10],i,j,k;

Dept. of CSE System Software & Operating System Lab – 17CSL67


41
printf("Enter the choice \n");
printf(" 1. Round Robin\n 2. SRT\n 3. Exit \n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Round Robin scheduling algorithm\n"); printf("Enter
number of processes:\n");
scanf("%d",&n);
printf("Enter burst time for sequences:");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
st[i]=bt[i]; //service time
}
printf("Enter time quantum:");
scanf("%d",&tq);
roundrobin(n,tq,st,bt);
break;

case 2:
printf("\n \n ---SHORTEST REMAINING TIME NEXT---\n \n ");
printf("\n \n Enter the number of processes: "); scanf("%d", &n);

srtf(n);
break;

case 3: exit(0);
}// end of switch
}// end of for
}//end of main()

void roundrobin(int n,int tq,int st[],int bt[])


{
int time=0;
int tat[10],wt[10],i,count=0,swt=0,stat=0,temp1,sq=0,j,k; float
awt=0.0,atat=0.0;
while(1)
{
for(i=0,count=0;i<n;i++)
{

Dept. of CSE System Software & Operating System Lab – 17CSL67


42
temp1=tq;
if(st[i]==0) // when service time of a process equals zero then
//count value is incremented
{
count++;
continue;
}
if(st[i]>tq) // when service time of a process greater than time
//quantum then time
st[i]=st[i]-tq; //quantum value subtracted from service time
else
if(st[i]>=0)
{
temp1=st[i]; // temp1 stores the service time of a process
st[i]=0; // making service time equals 0
}
sq=sq+temp1; // utilizing temp1 value to calculate turnaround time
tat[i]=sq; // turn around time
} //end of for
if(n==count) // it indicates all processes have completed their task because the
count value
break; // incremented when service time equals 0
} //end of while

for(i=0;i<n;i++) // to calculate the wait time and turnaround time of each process
{
wt[i]=tat[i]-bt[i]; // waiting time calculated from the turnaround time - burst time
swt=swt+wt[i]; // summation of wait time
stat=stat+tat[i]; // summation of turnaround time
}
awt=(float)swt/n; // average wait time
atat=(float)stat/n; // average turnaround time
printf("Process_no Burst time Wait time Turn around time\n");
for(i=0;i<n;i++)
printf("%d\t\t%d\t\t%d\t\t%d\n",i+1,bt[i],wt[i],tat[i]);
printf("Avg wait time is %f\n Avg turn around time is %f\n",awt,atat);
}// end of Round Robin
int chkprocess(int s) // function to check process remaining time is zero or not
{
int i;

Dept. of CSE System Software & Operating System Lab – 17CSL67


43
for(i = 1; i <= s; i++)
{
if(process[i].rem != 0)
return 1;
}
return 0;
} // end of chkprocess
int nextprocess() // function to identify the next process to be executed
{
int min, l, i;
min = 32000; //any limit assumed
for(i = 1; i <= no; i++)
{
if( process[i].rem!=0 && process[i].rem < min)
{
min = process[i].rem; l
= i;
}
}
return l;
} // end of nextprocess

void srtf(int n)
{
int i,j,k,time=0; float
tavg,wavg; for(i = 1; i
<= n; i++)
{
process[i].id = i;
printf("\n\nEnter the arrival time for process %d: ", i); scanf("%d",
&(process[i].arrival));
printf("Enter the burst time for process %d: ", i);
scanf("%d", &(process[i].burst)); process[i].rem =
process[i].burst;
}
for(i = 1; i <= n; i++)
{
for(j = i + 1; j <= n; j++)
{

if(process[i].arrival > process[j].arrival) // sort arrival time of a process

Dept. of CSE System Software & Operating System Lab – 17CSL67


44

{
temp = process[i]; process[i] = process[j];
process[j] = temp;
}
}
}
no = 0;
j = 1;
while(chkprocess(n) == 1)
{
if(process[no + 1].arrival == time)
{
while(process[no+1].arrival==time)
no++;
if(process[j].rem==0)
process[j].finish=time; j
= nextprocess();
}
if(process[j].rem != 0) // to calculate the waiting time of a process
{
process[j].rem--;
for(i = 1; i <= no; i++)
{
if(i != j && process[i].rem != 0) process[i].wait++;

}
}
else
{

process[j].finish = time;
j=nextprocess();
time--;
k=j;
}

time++;
}
process[k].finish = time;
printf("\n\n\t\t\t---SHORTEST REMAINING TIME FIRST---"); printf("\n\n Process
Arrival Burst Waiting Finishing turnaround Tr/Tb \n");
printf("%5s %9s %7s %10s %8s %9s\n\n", "id", "time", "time", "time", "time", "time");

Dept. of CSE System Software & Operating System Lab – 17CSL67


45
for(i = 1; i <= n; i++)
{
process[i].turnaround = process[i].wait + process[i].burst; // calc of turnaround
process[i].ratio = (float)process[i].turnaround / (float)process[i].burst;
printf("%5d %8d %7d %8d %10d %9d %10.1f ", process[i].id, process[i].arrival, process[i].burst,
process[i].wait, process[i].finish, process[i].turnaround, process[i].ratio);
tavg=tavg+ process[i].turnaround; //summation of turnaround time
wavg=wavg+process[i].wait; // summation of waiting time
printf("\n\n");

Dept. of CSE System Software & Operating System Lab – 17CSL67


45

tavg=tavg/n; // average turnaround time


wavg=wavg/n; // average wait time
printf("tavg=%f\t wavg=%f\n",tavg,wavg);
}// end of srtf

Output:
Enter the choice
1) Round Robin 2) SRT
3) Exit
1
Round Robin scheduling algorithm
**********************************
Enter number of processes:3
Enter burst time for sequences:24
3
3

Enter time quantum:4


Process_no Burst time Wait time Turnaround time
1 24 6 30
2 3 4 7
3 3 7 10
Avg wait time is 5.666667
Avg turnaround time is 15.666667
Enter the choice
1) Round Robin 2) SRT
3) Exit
2
---SHORTEST REMAINING TIME NEXT---
Enter the number of processes: 4
Enter the arrival time for process 1: 0
Enter the burst time for process 1: 8
Enter the arrival time for process 2: 1
Enter the burst time for process 2: 4
Enter the arrival time for process 3: 2
Enter the burst time for process 3: 9
Enter the arrival time for process 4: 3
Enter the burst time for process 4: 5
1 24 6 30
2 3 4 7
3 3 7 10
---SHORTEST REMAINING TIME FIRST---
Enter the number of processes: 4

Dept. of CSE System Software & Operating System Lab – 17CSL67


46

Enter the arrival time for process 1: 0


Enter the burst time for process 1: 8
Enter the arrival time for process 2: 1
Enter the burst time for process 2: 4
Enter the arrival time for process 3: 2
Enter the burst time for process 3: 9
Enter the arrival time for process 4: 3
Enter the burst time for process 4: 5
---SHORTEST REMAINING TIME NEXT---

Process Arrival Burst Waiting Finishing turnaround Tr/Tb


id time time time time time time
1 0 8 9 17 17 2.1
2 1 4 0 5 4 1.0
3 2 9 15 26 24 2.7
4 3 5 2 10 7 1.4

tavg=13.000000
wavg=6.500000
Using OpenMP

Dept. of CSE System Software & Operating System Lab – 17CSL67


8. Design, develop and implement a C/C++/Java program to implement Banker’s algorithm. Assume
suitable input required to demonstrate the results.
The Banker's algorithm, sometimes referred to as the detection algorithm, is a resource
allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by
simulating the allocation of predetermined maximum possible amounts of all resources, and then
makes an "s-state" check to test for possible deadlock conditions for all other pending activities, before
deciding whether allocation should be allowed to continue.
The algorithm was developed in the design process for the operating system and originally
described (in Dutch) in EWD108. When a new process enters a system, it must declare the maximum
number of instances of each resource type that it may ever claim; clearly, that number may not exceed
the total number of resources in the system. Also, when a process gets all its requested resources it
must return them in a finite amount of time.
#include <stdio.h>
#include <stdlib.h> int
main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10],
completed[10], safeSequence[10];
int p, r, i, j, process, count;
count = 0;

printf("Enter the no of processes : ");


scanf("%d", &p);

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


completed[i] = 0;

printf("\n\nEnter the no of resources : ");


scanf("%d", &r);

printf("\n\nEnter the Max Matrix for each process : "); for(i = 0; i


< p; i++)
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}

Dept. of CSE System Software & Operating System Lab – 17CSL67


48

printf("\n\nEnter the allocation for each process : "); for(i = 0; i <


p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}

printf("\n\nEnter the Available Resources : "); for(i


= 0; i < r; i++)
scanf("%d", &avail[i]);

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

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


need[i][j] = Max[i][j] - alloc[i][j];

do
{
printf("\n Max matrix:\tAllocation matrix:\n");

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


{
for( j = 0; j < r; j++) printf("%d
", Max[i][j]);
printf("\t\t");
for( j = 0; j < r; j++)
printf("%d ", alloc[i][j]);
printf("\n");
}

process = -1;

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


{
if(completed[i] == 0)//if not completed
{
process = i ;
for(j = 0; j < r; j++)
{
if(avail[j] < need[i][j])
{
process = -1;
break;
Dept. of CSE System Software & Operating System Lab – 17CSL67
49

}
}
}
if(process != -1)
break;
}

if(process != -1)
{
printf("\nProcess %d runs to completion!", process + 1); safeSequence[count]
= process + 1; count++;

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


{
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
}
while(count != p && process != -1);

if(count == p)
{
printf("\nThe system is in a safe state!!\n"); printf("Safe
Sequence : < ");
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]);
printf(">\n");
}
else
printf("\nThe system is in an unsafe state!!");

Output:
Enter the no of processes : 5
Enter the no of resources : 3
Enter the Max Matrix for each process :
For process 1 : 7
5
3
Dept. of CSE System Software Operating System Lab – 17CSL67
50

For process 2 : 3
2
2
For process 3 : 7
0
2
For process 4 : 2
2
2
For process 5 : 4
3
3

Enter the allocation for each process :


For process 1 : 0
1
0
For process 2 : 2
0
0
For process 3 : 3
0
2
For process 4 : 2
1
1
For process 5 : 0
0
2
Enter the Available Resources: 3
3
2
Max matrix: Allocation matrix:
753 0 10
322 2 00
702 3 02
222 2 11
433 0 02

Process 2 runs to completion!


Max matrix: Allocation matrix:
753 0 10
000 0 00
702 3 02
222 2 11

Dept. of CSE System Software & Operating System Lab – 17CSL67


51

433 002

Process 3 runs to completion!


Max matrix: Allocation matrix:
753 010
000 000
000 000
222 211
433 002

Process 4 runs to completion!


Max matrix: Allocation matrix:
753 010
000 000
000 000
000 000
433 002

Process 1 runs to completion!


Max matrix: Allocation matrix:
000 000
000 000
000 000
000 000
433 002

Process 5 runs to completion!


The system is in a safe state!!
Safe Sequence: < 2 3 4 1 5 >

Dept. of CSE System Software & Operating System Lab – 17CSL67


52

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.
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.
#include<stdio.h>
#include<stdlib.h>
void FIFO(char [ ],char [ ],int,int);
void lru(char [ ],char [ ],int,int);
void opt(char [ ],char [ ],int,int); int
main()
{
int ch,YN=1,i,l,f;
char F[10],s[25];

printf("\n\n\tEnter the no of empty frames: ");


scanf("%d",&f);
printf("\n\n\tEnter the length of the string: "); scanf("%d",&l);
printf("\n\n\tEnter the string: ");
scanf("%s",s);
for(i=0;i<f;i++)
F[i]=-1;
do
{

Dept. of CSE System Software & Operating System Lab – 17CSL67


53

printf("\n\n\t*********** MENU ***********");


printf("\n\n\t1:FIFO\n\n\t2:LRU
\n\n\t4:EXIT"); printf("\n\n\tEnter your choice: ");
scanf("%d",&ch);

switch(ch)
{
case 1:
for(i=0;i<f;i++)
{
F[i]=-1;
}
FIFO(s,F,l,f);
break;
case 2:
for(i=0;i<f;i++)
{
F[i]=-1;
}
lru(s,F,l,f);
break;
case 4:
exit(0);
}
printf("\n\n\tDo u want to continue IF YES PRESS 1\n\n\tIF NO PRESS 0 : "); scanf("%d",&YN);
}while(YN==1);return(0);
}
//FIFO
void FIFO(char s[],char F[],int l,int f)
{
int i,j=0,k,flag=0,cnt=0;
printf("\n\tPAGE\t FRAMES\t FAULTS");
for(i=0;i<l;i++)
{
for(k=0;k<f;k++)
{
if(F[k]==s[i])
flag=1;
}
if(flag==0)
{
printf("\n\t%c\t",s[i]);
F[j]=s[i];
Dept. of CSE System Software & Operating System Lab – 17CSL67
54

j++;
for(k=0;k<f;k++)
{
printf(" %c",F[k]);
}
printf("\tPage-fault%d",cnt);
cnt++;
}
else
{
flag=0;
printf("\n\t%c\t",s[i]);
for(k=0;k<f;k++)
{
printf(" %c",F[k]);
}
printf("\tNo page-fault");
}
if(j==f)
j=0;
}
}
//LRU
void lru(char s[],char F[],int l,int f)
{
int i,j=0,k,m,flag=0,cnt=0,top=0; printf("\n\tPAGE\t
FRAMES\t FAULTS");
for(i=0;i<l;i++)
{
for(k=0;k<f;k++)
{
if(F[k]==s[i])
{
flag=1;
break;
}
}
printf("\n\t%c\t",s[i]);
if(j!=f && flag!=1)
{
F[top]=s[i];
j++;
if(j!=f)
top++;
Dept. of CSE System Software & Operating System Lab – 17CSL67
55

}
else
{
if(flag!=1)
{
for(k=0;k<top;k++)
{
F[k]=F[k+1];
}
F[top]=s[i];
}
if(flag==1)
{
for(m=k;m<top;m++)
{
F[m]=F[m+1];
}
F[top]=s[i];
}
}
for(k=0;k<f;k++)
{
printf(" %c",F[k]);
}
if(flag==0)
{
printf("\tPage-fault%d",cnt);
cnt++;
}
else
printf("\tNo page fault");
flag=0;
}
}
Output:

Enter the no of empty frames: 3


Enter the length of the string: 5
Enter the string: hello

*********** MENU ***********


1:FIFO
2:LRU
4:EXIT

Dept. of CSE System Software & Operating System Lab – 17CSL67


56

Enter your choice: 1


PAGE FRAMES FAULTS
h h Page-fault 0

e h e Page-fault 1
l h e l Page-fault 2
l h e l No page-fault
o o e l Page-fault 3

Do u want to continue IF YES PRESS 1


IF NO PRESS 0 : 1

*********** MENU ***********


1:FIFO
2:LRU
4:EXIT
Enter your choice: 2
PAGE FRAMES FAULTS
h h Page-fault 0
e he Page-fault 1
l h e l Page-fault 2
l h e l No page fault
o e l o Page-fault 3

Do u want to continue IF YES PRESS 1


IF NO PRESS 0 : 1

*********** MENU ***********


1:FIFO
2:LRU
4:EXIT
Enter your choice: 4

Dept. of CSE System Software & Operating System Lab – 17CSL67


57

6.Extra Programs
1a) Design, develop and implement a C/C++/Java program to simulate a numerical calculator
#include <stdio.h>
void main()
{
char operator;
float num1, num2, result;

printf("Simulation of a Simple Calculator\n");


printf("*********************************\n");
printf("Enter two numbers \n"); scanf("%f %f",
&num1, &num2);
fflush(stdin);
printf("Enter the operator [+,-,*,/] \n");
scanf("%s", &operator); switch(operator)
{
case '+': result = num1 + num2; break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
break;
default : printf("Error in operationn");
break;
}
printf("\n %5.2f %c %5.2f = %5.2f\n", num1, operator, num2, result);
}
Output:
Simulation of a Simple Calculator
*********************************
Enter two numbers
2
3
Enter the operator [+, -, *, /]
+
2.00 + 3.00 = 5.00

Dept. of CSE System Software & Operating System Lab – 17CSL67


58

b) Design, develop and implement a C/C++/Java program to simulate page replacement technique
#include<stdio.h>
int n,nf;
int in[100];
int p[50]; int
hit=0; int
i,j,k;
int pgfaultcnt=0;

void getData()
{
printf("\nEnter length of page reference sequence:");
scanf("%d",&n);
printf("\nEnter the page reference sequence:");
for(i=0; i<n; i++)
scanf("%d",&in[i]);
printf("\nEnter no of frames:");
scanf("%d",&nf);
}

void initialize()
{
pgfaultcnt=0;
for(i=0; i<nf; i++)
p[i]=9999;
}

int isHit(int data)


{
hit=0;
for(j=0; j<nf; j++)
{
if(p[j]==data)
{
hit=1;
break;
}
}
return hit;
}

int getHitIndex(int data)


{
int hitind;
Dept. of CSE System Software & Operating System Lab – 17CSL67
59
for(k=0; k<nf; k++)
{
if(p[k]==data)
{
hitind=k;
break;
}
}
return hitind;
}

void dispPages()
{
for (k=0; k<nf; k++)
{
if(p[k]! =9999)
printf(" %d",p[k]);
}
}

void dispPgFaultCnt()
{
printf("\nTotal no of page faults:%d",pgfaultcnt);
}

void fifo()
{
initialize();
for(i=0; i<n; i++)
{
printf("\nFor %d :",in[i]);

if(isHit(in[i])==0)
{
for(k=0; k<nf-1; k++)
p[k]=p[k+1];
p[k]=in[i];
pgfaultcnt++;
dispPages();
}
else
printf("No page fault");
}
dispPgFaultCnt();}
Dept. of CSE System Software & Operating System Lab – 17CSL67
60

void optimal()
{
initialize(); int
near[50];
for(i=0; i<n; i++)
{
printf("\nFor %d :",in[i]);
if(isHit(in[i])==0)
{
for(j=0; j<nf; j++)
{
int pg=p[j];
int found=0;
for(k=i; k<n; k++)
{
if(pg==in[k])
{
near[j]=k;
found=1;
break;
}
else
found=0;
}
if(!found)
near[j]=9999;
}
int max=-9999; int
repindex; for(j=0;
j<nf; j++)
{
if(near[j]>max)
{
max=near[j];
repindex=j;
}
}
p[repindex]=in[i];
pgfaultcnt++;

dispPages();
}else
Dept. of CSE System Software & Operating System Lab – 17CSL67
61
}
dispPgFaultCnt();
}
printf("No page fault");
void lru()
{
initialize(); int
least[50];
for(i=0; i<n; i++)
{
printf("\nFor %d :",in[i]);
if(isHit(in[i])==0)
{
for(j=0; j<nf; j++)
{
int pg=p[j];
int found=0;
for(k=i-1; k>=0; k--)
{
if(pg==in[k])
{
least[j]=k;
found=1;
break;
}
else
found=0;
}
if(!found)
least[j]=-9999;
}
int min=9999; int
repindex; for(j=0;
j<nf; j++)
{
if(least[j]<min)
{
min=least[j];
repindex=j;
}
}
p[repindex]=in[i];
pgfaultcnt++;
Dept. of CSE System Software & Operating System Lab – 17CSL67
62

dispPages();
}
else
printf("No page fault!");
}
dispPgFaultCnt();
}

void lfu()
{
int usedcnt[100];
int least,repin,sofarcnt=0,bn; initialize();
for(i=0; i<nf; i++)
usedcnt[i]=0;

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


{

printf("\n For %d :",in[i]);


if(isHit(in[i]))
{
int hitind=getHitIndex(in[i]);
usedcnt[hitind]++; printf("No
page fault!");
}
else
{
pgfaultcnt++;
if(bn<nf)
{
p[bn]=in[i];
usedcnt[bn]=usedcnt[bn]+1;
bn++;
}
else
{
least=9999; for(k=0;
k<nf; k++)
if(usedcnt[k]<least)
{
least=usedcnt[k];
repin=k;
}
Dept. of CSE System Software & Operating System Lab – 17CSL67
63
p[repin]=in[i];
sofarcnt=0; for(k=0;
k<=i; k++)
if(in[i]==in[k])
sofarcnt=sofarcnt+1;
usedcnt[repin]=sofarcnt;
}

dispPages();
}

}
dispPgFaultCnt();
}

void secondchance()
{
int usedbit[50]; int
victimptr=0;
initialize(); for(i=0;
i<nf; i++)
usedbit[i]=0;
for(i=0; i<n; i++)
{
printf("\nFor %d:",in[i]);
if(isHit(in[i]))
{
printf("No page fault!");
int hitindex=getHitIndex(in[i]);
if(usedbit[hitindex]==0)
usedbit[hitindex]=1;
}
else
{
pgfaultcnt++;
if(usedbit[victimptr]==1)
{
do
{
usedbit[victimptr]=0;
victimptr++;
if(victimptr==nf)
victimptr=0;
}
Dept. of CSE System Software & Operating System Lab – 17CSL67
64

while(usedbit[victimptr]! =0);
}
if(usedbit[victimptr]==0)
{
p[victimptr]=in[i];
usedbit[victimptr]=1;
victimptr++;
}
dispPages();

}
if(victimptr==nf)
victimptr=0;
}
dispPgFaultCnt();
}

int main()
{
int choice;
while(1)
{
printf("\nPage Replacement Algorithms\n1.Enter
data\n2.FIFO\n3.Optimal\n4.LRU\n5.LFU\n6.Second Chance\n7.Exit\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
getData();
break;
case 2:
fifo();
break;
case 3:
optimal();
break;
case 4:
lru();
break;
case 5:
lfu();
break;
case 6:
Dept. of CSE System Software & Operating System Lab – 17CSL67
65

secondchance();
break;
default:
return 0;
break;
}
}
}
Output:
Page Replacement Algorithms
1.Enter data
2. FIFO
3. Optimal
4.LRU
5. LFU
6. Second Chance
7.Exit
Enter your choice:1

Enter length of page reference sequence:8

Enter the page reference sequence:2


3
4
2
3
5
6
2

Enter no of frames:3

Page Replacement Algorithms


1.Enter data
2. FIFO
3. Optimal
4.LRU
5. LFU
6. Second Chance
7.Exit
Enter your choice:2

For 2 : 2
For 3 : 2 3
For 4 : 2 3 4

Dept. of CSE System Software & Operating System Lab – 17CSL67


66

For 2 :No page fault


For 3 :No page fault
For 5 : 3 4 5
For 6 : 4 5 6
For 2 : 5 6 2
Total no of page faults:6
Page Replacement Algorithms
1.Enter data
2. FIFO
3. Optimal
4.LRU
5. LFU
6. Second Chance
7.Exit
Enter your choice:3

For 2 : 2
For 3 : 2 3
For 4 : 2 3 4
For 2 :No page fault
For 3 :No page fault
For 5 : 2 5 4
For 6 : 2 6 4
For 2 :No page fault
Total no of page faults:5
Page Replacement Algorithms
1.Enter data
2. FIFO
3. Optimal
4.LRU
5. LFU
6. Second Chance
7.Exit
Enter your choice:4

For 2 : 2
For 3 : 2 3
For 4 : 2 3 4
For 2 :No page fault!
For 3 :No page fault!
For 5 : 2 3 5
For 6 : 6 3 5
For 2 : 6 2 5
Total no of page faults:6
Page Replacement Algorithms
1.Enter data

Dept. of CSE System Software & Operating System Lab – 17CSL67


67

2. FIFO
3. Optimal
4.LRU
5. LFU
6. Second Chance
7.Exit
Enter your choice:5

For 2 : 2
For 3 : 2 3
For 4 : 2 3 4
For 2 :No page fault!
For 3 :No page fault!
For 5 : 2 3 5
For 6 : 2 3 6
For 2 :No page fault!
Total no of page faults:5
Page Replacement Algorithms
1.Enter data
2. FIFO
3. Optimal
4.LRU
5. LFU
6. Second Chance
7.Exit
Enter your choice:7

Dept. of CSE System Software & Operating System Lab – 17CSL67


68
7. 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.
 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 produces
either a corresponding Parse tree or an Error.
 What is the Syntax of a Language?
The Rules which tells whether a string is a valid Program or not are called the Syntax.
 What is the Semantics of a Language?
The Rules which gives meaning to programs are called the Semantics of a Language.
 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.
 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.
 How are the tokens recognized?
The tokens which are represented by a Regular Expressions are recognized in an input string by
means of a state transition Diagram and Finite Automata.
 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.

Dept. of CSE System Software & Operating System Lab – 17CSL67


69

 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

 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.
 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 represent the Non-Terminal symbols.
 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.
 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 have two non-terminals in the production rule. So the Terminal sandwiched between these

Dept. of CSE System Software & Operating System Lab – 17CSL67


70

two non-terminals must have some associability and precedence. This will help the parser to
understand which non-terminal would be expanded first.
 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 System Software & Operating System Lab – 17CSL67


71
8.Content Beyond Syllabus

1. Develop, Implement and execute a program using YACC tool to recognize strings i) a ii)

ab iii) aaab iv) abbb using the grammar a n b n (note: input n value).

Lex Part
%{
#include "y.tab.h"
%}
%%
a {return A;} b {return B;} [\n] return 0;
%%
%{
#include<stdio.h> #include<stdlib.h>
%}
%token A B
%%
YACC Part
input:s'\n' {printf("Successful Grammar\n");exit(0);} S:A S B
|;
%%
main()
{
printf("Enter string\n");
yyparse();
}

int yyerror()
{
printf("Error \n");
exit(0);
}
2. Design and Develop a program to create child process using fork () system call.

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main ()
{
Pid_t pid;

Dept. of CSE System Software & Operating System Lab – 17CSL67


72
Pid=fork();
If(pid<0)
{
Printf(“failed”);
exit();
}
If(pid==0)
{
Printf(“in child process”);
exelp(“/bin/ls”,”ls”);
}
else
{ printf(“parent process”);
Wait(NULL);
Printf(“child completes”);
exit();
}
}

*****ALL THE BEST*****

Dept. of CSE System Software & Operating System Lab – 17CSL67

You might also like