54
JNTUWORLD JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA III Year B. Tech. Computer Science and Engineering – I Sem. OPERATING SYSTEM & COMPILER DESIGN LAB PART – A: 1. Design a Lexical analyzer for the given language. The lexical analyzer should ignore redundant spaces, tabs and newlines. It should also ignore comments. Although the syntax specification states that identifiers can be arbitrarily long, you may restrict the length to some reasonable value. 2. Implement the lexical analyzer using JLex, flex or lex or other lexical analyzer generating tools. 3. Design Predictive parser for the given language 4. Design LALR bottom up parser for the given language. 5. Convert the BNF rules into Yacc form and write code to generate abstract syntax tree. PART- B: 1. Simulate the following CPU scheduling algorithms a) Round Robin b) SJF c) FCFS d) Priority 2. Simulate all file allocation strategies a) Sequentialb) Indexed c) Linked 3. Simulate MVT and MFT 4. Simulate all File Organization Techniques a) Single level directory b) Two level c) Hierarchical d) DAG 5. Simulate Bankers Algorithm for Dead Lock Avoidance 6. Simulate Bankers Algorithm for Dead Lock Prevention 7. Simulate all page replacement algorithms a) FIFO b) LRU c) LFU Etc. 8. Simulate Paging Technique of memory management. www.jntuworld.com www.jntuworld.com

CD Lab Manual

Embed Size (px)

Citation preview

JNTUWORLD

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY KAKINADA

III Year B. Tech. Computer Science and Engineering – I Sem.

OPERATING SYSTEM & COMPILER DESIGN LAB PART – A: 1. Design a Lexical analyzer for the given language. The lexical analyzer should ignore

redundant spaces, tabs and newlines. It should also ignore comments. Although the syntax specification states that identifiers can be arbitrarily long, you may restrict the length to some reasonable value.

2. Implement the lexical analyzer using JLex, flex or lex or other lexical analyzer generating tools.

3. Design Predictive parser for the given language 4. Design LALR bottom up parser for the given language. 5. Convert the BNF rules into Yacc form and write code to generate abstract syntax tree. PART- B: 1. Simulate the following CPU scheduling algorithms

a) Round Robin b) SJF c) FCFS d) Priority 2. Simulate all file allocation strategies

a) Sequentialb) Indexed c) Linked 3. Simulate MVT and MFT 4. Simulate all File Organization Techniques

a) Single level directory b) Two level c) Hierarchical d) DAG 5. Simulate Bankers Algorithm for Dead Lock Avoidance 6. Simulate Bankers Algorithm for Dead Lock Prevention 7. Simulate all page replacement algorithms

a) FIFO b) LRU c) LFU Etc. Q 8. Simulate Paging Technique of memory management.

www.jntuworld.com

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

TABLE OF CONTENTS(As per syllabus)

S.No TOPIC Wee

kPageNo.

1System Requirements 3

2Lab Objectives 4

3Design a lexical analyzer for given language .the lexical analyzer should ignore redundant spaces, tabs and new lines. 5

4

Implement the lexical analyzer using JLex, flex or other lexical analyzer generating tools. 8

5Design predictive parser for the given language 11

6Design a LALR bottom up parser for the given language 16

7

Convert the BNF rules into Yacc form and write code to generate abstract syntax tree. 18

8A program to generate machine code 25

9

10

11

12

13

14

15

16

17

18

2

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

System Requirements

1. Intel based destktop PC of 166MHz or faster processor with at least 64 MB RAM and 100 MB free disk space.

2. C++ compiler and JDK kit.

3

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

Lab Objectives

1. To provide an Understanding of the language translation peculiarities by designing complete translator for mini language.

2. To provide an understanding of the design aspect of operating system.

4

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

1)A Program to Design Lexical Analyzer.

#include<string.h>#include<ctype.h>#include<stdio.h>void keyword(char str[10]){if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||strcmp("double",str)==0||strcmp("static",str)==0||strcmp("switch",str)==0||strcmp("case",str)==0)

printf("\n%s is a keyword",str);else

printf("\n%s is an identifier",str);}main(){

FILE *f1,*f2,*f3;char c,str[10],st1[10];int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;

printf("\nEnter the c program");/*gets(st1);*/f1=fopen("input","w");while((c=getchar())!=EOF)

putc(c,f1);fclose(f1);f1=fopen("input","r");f2=fopen("identifier","w");f3=fopen("specialchar","w");while((c=getc(f1))!=EOF){

if(isdigit(c)){

tokenvalue=c-'0';c=getc(f1);while(isdigit(c)){

tokenvalue*=10+c-'0';c=getc(f1);

}num[i++]=tokenvalue;ungetc(c,f1);

}else if(isalpha(c)){

putc(c,f2);c=getc(f1);

5

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

while(isdigit(c)||isalpha(c)||c=='_'||c=='$'){

putc(c,f2);c=getc(f1);

}putc(' ',f2);ungetc(c,f1);

}else if(c==' '||c=='\t')

printf(" ");

else if(c=='\n')lineno++;

elseputc(c,f3);

}fclose(f2);fclose(f3);fclose(f1);printf("\nThe no's in the program are");for(j=0;j<i;j++)

printf("%d",num[j]);printf("\n");f2=fopen("identifier","r");k=0;printf("The keywords and identifiersare:");while((c=getc(f2))!=EOF){

if(c!=' ')str[k++]=c;

else{ str[k]='\0';

keyword(str);k=0;

}}fclose(f2);f3=fopen("specialchar","r");printf("\nSpecial characters are");while((c=getc(f3))!=EOF)

printf("%c",c);printf("\n");fclose(f3);printf("Total no. of lines are:%d",lineno);

}

6

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

Output:

Enter the C program a+b*c

Ctrl-D

The no’s in the program are:

The keywords and identifiers are:a is an identifier and terminalb is an identifier and terminalc is an identifier and terminal

Special characters are:+ *

Total no. of lines are: 1

7

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

2)Implement the Lexical Analyzer Using Lex Tool.

/* program name is lexp.l */%{ /* program to recognize a c program */ int COMMENT=0;%}identifier [a-zA-Z][a-zA-Z0-9]*

%%

#.* { printf("\n%s is a PREPROCESSOR DIRECTIVE",yytext);}int |float |char |double |while |for |do |if |break |continue |void |switch |case |long |struct |const |typedef |return |else |goto {printf("\n\t%s is a KEYWORD",yytext);}"/*" {COMMENT = 1;} /*{printf("\n\n\t%s is a COMMENT\n",yytext);}*/

"*/" {COMMENT = 0;} /* printf("\n\n\t%s is a COMMENT\n",yytext);}*/{identifier}\( {if(!COMMENT)printf("\n\nFUNCTION\n\t%s",yytext);}

\{ {if(!COMMENT) printf("\n BLOCK BEGINS");}

\} {if(!COMMENT) printf("\n BLOCK ENDS");}

8

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}\".*\" {if(!COMMENT) printf("\n\t%s is a STRING",yytext);}

[0-9]+ {if(!COMMENT) printf("\n\t%s is a NUMBER",yytext);}

\)(\;)? {if(!COMMENT) printf("\n\t");ECHO;printf("\n");}

\( ECHO;

= {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext);}

\<= |\>= |\< |== |\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}

%%

int main(int argc,char **argv){ if (argc > 1) { FILE *file; file = fopen(argv[1],"r"); if(!file) { printf("could not open %s \n",argv[1]); exit(0); } yyin = file; } yylex(); printf("\n\n"); return 0;}int yywrap(){ return 0;}

9

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

Input:

$vi var.c

#include<stdio.h>main(){ int a,b;}

Output:

$lex lex.l$cc lex.yy.c$./a.out var.c

#include<stdio.h> is a PREPROCESSOR DIRECTIVE

FUNCTION

main ( )

BLOCK BEGINS

int is a KEYWORD

a IDENTIFIER b IDENTIFIER

BLOCK ENDS

10

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

3) Implementation of Predictive Parser.

#include<stdio.h>#include<ctype.h>#include<string.h>#include<stdlib.h>#define SIZE 128#define NONE -1#define EOS '\0'#define NUM 257#define KEYWORD 258#define ID 259#define DONE 260#define MAX 999char lexemes[MAX];char buffer[SIZE];int lastchar=-1;int lastentry=0;int tokenval=DONE;int lineno=1;int lookahead;struct entry{ char *lexptr; int token;}symtable[100];struct entry keywords[]={"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,"int",KEYWORD,"float",KEYWORD,"double",KEYWORD,"char",KEYWORD,"struct",KEYWORD,"return",KEYWORD,0,0};void Error_Message(char *m){ fprintf(stderr,"line %d, %s \n",lineno,m); exit(1);}int look_up(char s[ ]){ int k; for(k=lastentry;k>0;k--) if(strcmp(symtable[k].lexptr,s)==0) return k; return 0;}int insert(char s[ ],int tok){ int len;

11

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

len=strlen(s); if(lastentry+1>=MAX) Error_Message("Symbpl table is full"); if(lastchar+len+1>=MAX) Error_Message("Lexemes array is full"); lastentry=lastentry+1; symtable[lastentry].token=tok; symtable[lastentry].lexptr=&lexemes[lastchar+1]; lastchar=lastchar+len+1; strcpy(symtable[lastentry].lexptr,s); return lastentry;}/*void Initialize(){ struct entry *ptr; for(ptr=keywords;ptr->token;ptr+1) insert(ptr->lexptr,ptr->token);}*/int lexer(){ int t; int val,i=0; while(1) { t=getchar(); if(t==' '||t=='\t'); else if(t=='\n') lineno=lineno+1; else if(isdigit(t)) { ungetc(t,stdin); scanf("%d",&tokenval); return NUM; } else if(isalpha(t)) { while(isalnum(t)) { buffer[i]=t; t=getchar(); i=i+1; if(i>=SIZE) Error_Message("Compiler error"); } buffer[i]=EOS; if(t!=EOF)

12

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

ungetc(t,stdin); val=look_up(buffer); if(val==0) val=insert(buffer,ID); tokenval=val; return symtable[val].token; } else if(t==EOF) return DONE; else { tokenval=NONE; return t; } }}void Match(int t){ if(lookahead==t) lookahead=lexer(); else Error_Message("Syntax error");}void display(int t,int tval){ if(t=='+'||t=='-'||t=='*'||t=='/') printf("\nArithmetic Operator: %c",t); else if(t==NUM) printf("\n Number: %d",tval); else if(t==ID) printf("\n Identifier: %s",symtable[tval].lexptr); else printf("\n Token %d tokenval %d",t,tokenval);}void F(){ //void E(); switch(lookahead) { case '(' : Match('('); E(); Match(')'); break; case NUM : display(NUM,tokenval); Match(NUM); break;

13

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

case ID : display(ID,tokenval); Match(ID); break; default : Error_Message("Syntax error"); }}void T(){ int t; F(); while(1) { switch(lookahead) { case '*' : t=lookahead; Match(lookahead); F(); display(t,NONE); continue; case '/' : t=lookahead; Match(lookahead); display(t,NONE); continue; default : return; } }}void E(){ int t; T(); while(1) { switch(lookahead) { case '+' : t=lookahead; Match(lookahead); T(); display(t,NONE); continue; case '-' : t=lookahead; Match(lookahead); T(); display(t,NONE); continue; default : return;

14

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

} }}void parser(){ lookahead=lexer(); while(lookahead!=DONE) { E(); Match(';'); }}main(){ char ans[10]; printf("\n Program for recursive decent parsing "); printf("\n Enter the expression "); printf("And place ; at the end\n"); printf("Press Ctrl-Z to terminate\n"); parser();}

Output:

Program for recursive decent parsingEnter the expression And place ; at the endPress Ctrl-Z to terminatea+b*c;Identifier: aIdentifier: bIdentifier: cArithmetic Operator: *Arithmetic Operator: +2*3;Number: 2Number: 3Arithmetic Operator: *+3;line 5,Syntax errorCtrl-Z

15

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

4) Design LALR Bottom up Parser .

<parser.l>

%{#include<stdio.h>#include "y.tab.h"

%}%%[0-9]+ {yylval.dval=atof(yytext);

return DIGIT;}

\n|. return yytext[0];%%

<parser.y>

%{/*This YACC specification file generates the LALR parser for the program

considered in experiment 4.*/ #include<stdio.h>%}%union{

double dval;}

%token <dval> DIGIT%type <dval> expr%type <dval> term%type <dval> factor

%%

line: expr '\n' {printf("%g\n",$1);}

;expr: expr '+' term {$$=$1 + $3 ;}

| term ;

term: term '*' factor {$$=$1 * $3 ;} | factor ;

factor: '(' expr ')' {$$=$2 ;}

16

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

| DIGIT ;

%%int main(){

yyparse();}

yyerror(char *s){

printf("%s",s);}

Output:

$lex parser.l$yacc –d parser.y$cc lex.yy.c y.tab.c –ll –lm$./a.out2+35.0000

17

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

5) Convert The BNF rules into Yacc form and write code to generate abstract syntax tree.

<int.l>%{ #include"y.tab.h" #include<stdio.h> #include<string.h> int LineNo=1;%}

identifier [a-zA-Z][_a-zA-Z0-9]*number [0-9]+|([0-9]*\.[0-9]+)%%

main\(\) return MAIN;

if return IF;else return ELSE;while return WHILE;

int |char |float return TYPE;

{identifier} {strcpy(yylval.var,yytext); return VAR;}

{number} {strcpy(yylval.var,yytext); return NUM;}

\< |\> |\>= |\<= | == {strcpy(yylval.var,yytext); return RELOP;}

[ \t] ;\n LineNo++;

. return yytext[0];

%%

18

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

<int.y>

%{#include<string.h>#include<stdio.h>struct quad{ char op[5]; char arg1[10]; char arg2[10]; char result[10];}QUAD[30];struct stack{ int items[100]; int top;}stk;

int Index=0,tIndex=0,StNo,Ind,tInd;extern int LineNo;%}

%union{ char var[10];}%token <var> NUM VAR RELOP%token MAIN IF ELSE WHILE TYPE

%type <var> EXPR ASSIGNMENT CONDITION IFST ELSEST WHILELOOP%left '-' '+'%left '*' '/'

%%

PROGRAM : MAIN BLOCK;

BLOCK: '{' CODE '}';

CODE: BLOCK | STATEMENT CODE | STATEMENT;STATEMENT: DESCT ';' | ASSIGNMENT ';'

19

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

| CONDST | WHILEST;

DESCT: TYPE VARLIST;

VARLIST: VAR ',' VARLIST | VAR ;

ASSIGNMENT: VAR '=' EXPR{ strcpy(QUAD[Index].op,"="); strcpy(QUAD[Index].arg1,$3); strcpy(QUAD[Index].arg2,""); strcpy(QUAD[Index].result,$1); strcpy($$,QUAD[Index++].result); };

EXPR: EXPR '+' EXPR {AddQuadruple("+",$1,$3,$$);} | EXPR '-' EXPR {AddQuadruple("-",$1,$3,$$);} | EXPR '*' EXPR {AddQuadruple("*",$1,$3,$$);} | EXPR '/' EXPR {AddQuadruple("/",$1,$3,$$);} | '-' EXPR {AddQuadruple("UMIN",$2,"",$$);} | '(' EXPR ')' {strcpy($$,$2);} | VAR | NUM;

CONDST: IFST{Ind=pop();sprintf(QUAD[Ind].result,"%d",Index);Ind=pop();sprintf(QUAD[Ind].result,"%d",Index);}| IFST ELSEST;

IFST: IF '(' CONDITION ')' {strcpy(QUAD[Index].op,"==");strcpy(QUAD[Index].arg1,$3);strcpy(QUAD[Index].arg2,"FALSE");strcpy(QUAD[Index].result,"-1");push(Index);Index++;

20

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

}

BLOCK {strcpy(QUAD[Index].op,"GOTO");strcpy(QUAD[Index].arg1,"");strcpy(QUAD[Index].arg2,"");strcpy(QUAD[Index].result,"-1");push(Index);Index++;};

ELSEST: ELSE{tInd=pop();Ind=pop();push(tInd);sprintf(QUAD[Ind].result,"%d",Index);}BLOCK{Ind=pop();sprintf(QUAD[Ind].result,"%d",Index);};

CONDITION: VAR RELOP VAR {AddQuadruple($2,$1,$3,$$); StNo=Index-1; } | VAR | NUM ;WHILEST: WHILELOOP{ Ind=pop(); sprintf(QUAD[Ind].result,"%d",StNo); Ind=pop(); sprintf(QUAD[Ind].result,"%d",Index); };WHILELOOP: WHILE '(' CONDITION ')' { strcpy(QUAD[Index].op,"=="); strcpy(QUAD[Index].arg1,$3); strcpy(QUAD[Index].arg2,"FALSE"); strcpy(QUAD[Index].result,"-1"); push(Index); Index++; }BLOCK {

21

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

strcpy(QUAD[Index].op,"GOTO"); strcpy(QUAD[Index].arg1,""); strcpy(QUAD[Index].arg2,""); strcpy(QUAD[Index].result,"-1"); push(Index); Index++; } ;%%extern FILE *yyin;int main(int argc,char *argv[]){ FILE *fp; int i; if(argc>1) { fp=fopen(argv[1],"r"); if(!fp) { printf("\n File not found"); exit(0); } yyin=fp; } yyparse(); printf("\n\n\t\t ----------------------------""\n\t\t Pos Operator Arg1 Arg2 Result" "\n\t\t --------------------"); for(i=0;i<Index;i++) { printf("\n\t\t %d\t %s\t %s\t %s\t %s",i,QUAD[i].op,QUAD[i].arg1,QUAD[i].arg2,QUAD[i].result); } printf("\n\t\t -----------------------"); printf("\n\n"); return 0;}void push(int data){ stk.top++; if(stk.top==100) { printf("\n Stack overflow\n"); exit(0); } stk.items[stk.top]=data;}

22

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

int pop(){ int data; if(stk.top==-1) { printf("\n Stack underflow\n"); exit(0); } data=stk.items[stk.top--]; return data;}void AddQuadruple(char op[5],char arg1[10],char arg2[10],char result[10]){ strcpy(QUAD[Index].op,op); strcpy(QUAD[Index].arg1,arg1); strcpy(QUAD[Index].arg2,arg2); sprintf(QUAD[Index].result,"t%d",tIndex++); strcpy(result,QUAD[Index++].result);}yyerror(){ printf("\n Error on line no:%d",LineNo);}

Input:

$vi test.cmain(){ int a,b,c; if(a<b) { a=a+b; } while(a<b) { a=a+b; } if(a<=b) { c=a-b; } else { c=a+b;

23

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

}}Output:

$lex int.l$yacc –d int.y$gcc lex.yy.c y.tab.c –ll –lm$./a.out test.c

Pos Operator Arg1 Arg2 Result

0 < a b to

1 == to FALSE 5

2 + a b t1

3 = t1 a

4 GOTO 5

5 < a b t2

6 == t2 FALSE 10

7 + a b t3

8 = t3 a

9 GOTO 5

10 <= a b t4

11 == t4 FALSE 15

12 - a b t5

13 = t5 c

14 GOTO 17

15 + a b t3

16 = t6 c

___________________________________________________

24

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

6) A Program to Generate Machine Code.

#include<stdio.h>#include<stdlib.h>#include<string.h>int label[20];int no=0;int main(){ FILE *fp1,*fp2; char fname[10],op[10],ch; char operand1[8],operand2[8],result[8]; int i=0,j=0; printf("\n Enter filename of the intermediate code"); scanf("%s",&fname); fp1=fopen(fname,"r"); fp2=fopen("target.txt","w"); if(fp1==NULL || fp2==NULL) { printf("\n Error opening the file"); exit(0); } while(!feof(fp1)) { fprintf(fp2,"\n"); fscanf(fp1,"%s",op); i++; if(check_label(i)) fprintf(fp2,"\nlabel#%d",i); if(strcmp(op,"print")==0) { fscanf(fp1,"%s",result); fprintf(fp2,"\n\t OUT %s",result); } if(strcmp(op,"goto")==0) { fscanf(fp1,"%s %s",operand1,operand2); fprintf(fp2,"\n\t JMP %s,label#%s",operand1,operand2); label[no++]=atoi(operand2); } if(strcmp(op,"[]=")==0) { fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n\t STORE %s[%s],%s",operand1,operand2,result); } if(strcmp(op,"uminus")==0)

25

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

{ fscanf(fp1,"%s %s",operand1,result); fprintf(fp2,"\n\t LOAD -%s,R1",operand1); fprintf(fp2,"\n\t STORE R1,%s",result); } switch(op[0]) { case '*': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD",operand1); fprintf(fp2,"\n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t MUL R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result); break; case '+': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t ADD R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result); break; case '-': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t SUB R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result); break; case '/': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t DIV R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result); break; case '%': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n \t LOAD %s,R1",operand2); fprintf(fp2,"\n \t DIV R1,R0"); fprintf(fp2,"\n \t STORE R0,%s",result); break; case '=': fscanf(fp1,"%s %s",operand1,result); fprintf(fp2,"\n\t STORE %s %s",operand1,result); break; case '>': j++; fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n\t JGT %s,label#%s",operand2,result); label[no++]=atoi(result); break;

26

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

case '<': fscanf(fp1,"%s %s %s",operand1,operand2,result); fprintf(fp2,"\n \t LOAD %s,R0",operand1); fprintf(fp2,"\n\t JLT %s,label#%d",operand2,result); label[no++]=atoi(result); break; } } fclose(fp2); fclose(fp1); fp2=fopen("target.txt","r"); if(fp2==NULL) { printf("Error opening the file\n"); exit(0); } do { ch=fgetc(fp2); printf("%c",ch); }while(ch!=EOF); fclose(fp1); return 0;}int check_label(int k){ int i; for(i=0;i<no;i++) { if(k==label[i]) return 1; } return 0;}

Input:

$vi int.txt=t1 2[]=a 0 1[]=a 1 2[]=a 2 3*t1 6 t2+a[2] t2 t3

27

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

-a[2] t1 t2/t3 t2 t2uminus t2 t2print t2goto t2 t3=t3 99uminus 25 t2*t2 t3 t3uminus t1 t1+t1 t3 t4print t4

Output:

Enter filename of the intermediate code: int.txt

STORE t1,2STORE a[0],1STORE a[1],2STORE a[2],3

LOAD t1,R0LOAD 6,R1ADD R1,R0STORE R0,t3

LOAD a[2],R0LOAD t2,R1ADD R1,R0STORE R0,t3

LOAD a[t2],R0LOAD t1,R1SUB R1,R0STORE R0,t2

LOAD t3,R0LOAD t2,R1DIV R1,R0STORE R0,t2

LOAD t2,R1STORE R1,t2LOAD t2,R0JGT 5,label#11

28

www.jntuworld.com

www.jntuworld.com

JNTUWORLD

CD LAB PROGRAMS

Label#11: OUT t2 JMP t2,label#13Label#13: STORE t3,99 LOAD 25,R1 STORE R1,t2 LOAD t2,R0 LOAD t3,R1 MUL R1,R0 STORE R0,t3 LOAD t1,R1 STORE R1,t1 LOAD t1,R0 LOAD t3,R1 ADD R1,R0 STORE R0,t4 OUT t4

29

www.jntuworld.com

5

OPERATING SYSTEMS

Experiment : 1

Simulate the following CPU Scheduling Algorithms

a) FCFS b) SJF c) Round Robin d) Priority

CPU SCHEDULING

Maximum CPU utilization obtained with multiprogramming

CPU–I/O Burst Cycle – Process execution consists of a cycle of

CPU execution and I/O wait

CPU burst distribution

Alternating Sequence of CPU And I/O Bursts

PART - B

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

6

CCPPUU SScchheedduulleerr

• Selects from among the processes in memory that are ready to execute,

and allocates the CPU to one of them

• CPU scheduling decisions may take place when a process:

1. Switches from running to waiting state 2. Switches from running to ready state 3. Switches from waiting to ready 4. Terminates

• Scheduling under 1 and 4 is nonpreemptive

• All other scheduling is preemptive

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

7

Dispatcher

• Dispatcher module gives control of the CPU to the process selected by the

short-term scheduler; this involves:

� switching context

� switching to user mode

� jumping to the proper location in the user

program to restart that program

• Dispatch latency – time it takes for the dispatcher to stop one process

and start another running SCHEDULING CRITERIA CPU utilization – keep the CPU as busy as possible

„ Throughput – # of processes that complete their execution per time unit

„ Turnaround time – amount of time to execute a particular process

„ Waiting time – amount of time a process has been waiting in the ready

queue

„ Response time – amount of time it takes from when a request was

submitted until the first response is produced, not output (for time-sharing

environment)

Optimization Criteria

Max CPU utilization

Max throughput

Min turnaround time

Min waiting time

Min response time

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

8

a) First-Come, First-Served (FCFS) Scheduling Process Burst Time P1 24

P2 3

P3 3

Suppose that the processes arrive in the order: P1 , P2 , P3

The Gantt Chart for the schedule is: 0 24 27 30

Waiting time for P1 = 0; P2 = 24; P3 = 27

Average waiting time: (0 + 24 + 27)/3 = 17 First Come First Serve scheduling algorithm :

Step 1: Assign the first term to each process.

Step2: Take process into consideration

Step 3: Consider next process

Add the previous process first time value to WAT variable

Step4 : Go to step 3 into all the process executed.

Step 5: Calculate average waiting teme =wat variable / no.of process.

b) SHORTEST JOB FIRST ALGORITHM

Step 1: Assign burst time to each process

Step2: Find the minimum burst time among all the burst time.

Execute that process which is having minimum

Initializes 0 to wait variable

Step 3: Find next minimum burst time

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

9

• If the two process having same burst time, consider the first coming

process in to consideration

• Add the previous burst time value to wait variable

• Continue till all the process are executed

Step 4: Calculate the average waiting time = wat variable / no.of process

Example of Non Preemptive SJF

Process Arrival Time Burst Time

P1 0.0 7

P2 2.0 4

P3 4.0 1

P4 3.0 4

P1 P3 P2 P4

0 7 8 12 16

Example of Preemptive SJF

Process Arrival Time Burst Time

P1 0.0 7

P2 2.0 4

P3 4.0 1

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

10

P4 3.0 4

P1 P2 P3 P2 P4 P1

0 2 4 5 7 11 16

Average waiting time = (9 + 1 + 0 +2)/4 = 3

Round Robin (RR)

• Each process gets a small unit of

CPU time (time quantum), usually

10-100 milliseconds. After this time

has elapsed, the process is

preempted and added to the end of

the ready queue.

• If there are n processes in the ready

queue and the time quantum is q,

then each process gets 1/n of the

CPU time in chunks of at most q

time units at once. No process

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

11

Example of RR with time quantum=3

Process Burst time

aaa 4

Bbb 3

Ccc 2

Ddd 5

Eee 1

Round Robin Scheduling Algorithm:

Step1: Assign the burst times to each process

Step2: Input the Quantum time

Step3: Start with burst process

1. If burst time > Quantum time

Burst time of process = burst time of process -

quantum time

If it is initial process

add 0 to wat

Else

Add quantum to wat

Switch to next process

Else

If first time <=0

Quit that process from quantum

Else

Add burst that process from the variable

2. repeat the steps 3 until all the process

quit from the queue

Step 4: calculate the average waiting time = wat variable / no. of processors.

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

12

INPUT :

enter the process name : aaa

enter the processing time : 4

enter the process name : bbb

enter the processing time : 3

enter the process name : ccc

enter the processing time : 2

enter the process name : ddd

enter the processing time : 5

enter the process name : eee

enter the processing time : 1

Expected Output :

p_name p_time w_time

aaa 4 9

bbb 3 3

ccc 2 6

ddd 5 10

eee 1 11

total waiting time : 39

average waiting time : 7.8000

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

13

Priority Scheduling

• A priority number (integer) is associated

with each process

• The CPU is allocated to the process with

the highest priority (smallest integer ≡

highest priority)

– Preemptive

– nonpreemptive

• SJF is a priority scheduling where priority

is the predicted next CPU burst time

• Problem ≡ Starvation – low priority

Priority Scheduling Algorithm:

Step1 : Assign burst time and priority value to each process

Step 2: Select highest priority value from the ready queue.

Step 3: if priority value is same to the two or more processors then

Consider the first coming processor and execute that

If it is first processor

Add 0 to the wat variable

Else

Add burst time to the wat variable.

Repeat step 3 until all the processors executed.

Step 4: calculate the average waiting time = wat variable / no. of processors.

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

14

Experiment 2: Simulate all file Allocation strategies:

a) Sequential b) Indexed c) Linked

File Allocation Strategies:

The main problem is how to allocate disk space to the files so that disk space is

utilized effectively band files can be accessed quickly. We have 3 space

allocation method.

1. Contiguous allocation (Sequential)

It requires each file to occupy a set of contiguous blocks on the hard disk

where disk address define a linear ordering on the disk.

Disadvantages:

i. Difficult for finding space for a new file.

ii. Internal and external fragmentation will be occurred.

Indexed allocation

In linked allocation it is difficult to maintain FAT – so instead of that method

indexed allocation method is used. Indexed allocation method solves all the

problems in the linked allocation by bringing all the pointers together into one

location called index block.

Linked Allocation

Linked allocation of disk space overcomes all the problems of contiguous

allocation. In linked allocation each file is a linked list of disk blocks where the

disk blocks may be scattered anywhere on the disk. The directory contains a

pointer to the first and last blocks of the file.

Disadvantages : Space required to maintain pointers.

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

15

3) Simulate MFT and MVT.

Memory: Multiple Programming with fixed Number of Tasks (MFT)

Algorithm

Background:

IBM in their Mainframe Operating System OS/MFT implements the MFT

concept. OS/MFT uses Fixed partitioning concept to load programs into

Main memory.

Fixed Partitioning:

• In fixed partitioning concept, RAM is divided into set of fixed

partition of equal Size

• Programs having the Size Less than the partition size are loaded

into Memory

• Programs Having Size more then the size of Partitions Size is

rejected

• The program having the size less than the partition size will lead to

internal Fragmentation.

• If all partitions are allocated and a new program is to be loaded, the

program that lead to Maximum Internal Fragmentation can be

replaced

Specification

Input Step-1

o Memory Size (memsize)

o Partition Size (parsize)

o

Process Step-1

� Compute number of partitions (n partitions)

� = memsize/parsize

� Create a Partition Table having n partition

entries’

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

16

Partition

Number

Partition

Size

Process

Number

scheduled

Program Size Internal

Fragment

Size

1 2 3 4 5

The column 3,4 and 5 initially will be blank

Input Step-2

o Number of Process (n processes) and their Sizes (process Size)

Process Step-3

o Create Process table having nprocesses

Process

Number

Process

Size Pratition

Number

Allocated

Partition

Size

Internal

Fragment

Size

Allocated

Flag

1 2 3 4 5

Column 3,4,5 and 6 initially will be blank

Process Step-2

o Allocate processes to Pratitions

o If the process Size is>Partition size Allocated Flag = o (over Size)

o If no partition exists Allocated flag =A and calculate the internal fragment

size. Update the process row and Pratition row

Process Step-3

o Print the Process table and Partition table

o

Process step-4

o This step is done a LOOP till the user wants to exist

o Input 1 =Continue,2=Stop

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

17

o If 2 Break

o Read the Size of the Program>partition size then Reject

o If there is a unallocated partition, allocate the a partition and update the

partition and process table

o If no partition is available, select the partition with maximum

fragmentation and update the process table and partition table

o Print process table and partition Table.

Memory: multiple Programming with Varible Number of Tasks (MFT)

Algorithm

Background:

IBM in their Mainframe Operating ‘System OS/MVT implements the MVT

concept. OSIMVT uses Dynamic Partition concept to load programs into Main

memory.

Dynamic Partitioning:

o Initially RAM is portioned according to the of programs to be loaded into

Memory till such time no other program can be loaded.

o The Left over Memory is called a hole which is too small too fit any

process.

o When a new program is to be into Memory Look for the partition, Which

Leads to least External fragmentation and load the Program.

o The space that is not used in a partition is called as External Fragmentation

Specification

Input Step-1

o Memory Size (memsize)

o Number of Processes (n processes)

Input Step-2

o Create Process table having n processes entries

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

18

o

Process

Number

Process

Size

Partition

Number

Allocation

Partition

Size

External

Fragmentt

Size

Allocated

Flag

1 2 3 4 5 6

Column 3,4,5 and 6 initially will be blank

Process Step-2

o For each of the process do the following steps

o Input the process Size.

o Update the process Table with Process number and process size, partition

number and size=0,Allocated Flag=N, fragment size=0

o

Process Step-3

o Create a partitions Table having One Row to start with

o

Partition

Number

Partition

Size

Process

Number

Scheduled

Program

Size

External

Fragment

Size

1 2 3 4 5

Process Step-4

o Available Memory = Memory Size

o Partitionnum=0

o For each of the process the following steps are undertaken

o If Available memory> process Size

o If no row Exists

� Create a new row in Partition table

� Partitionnum = Partitionnum+1

� Update a partition equel to the size of the program number,

partition Size, and external fragment=0

� Update the process table with partition number and size

and Allocated Flag = A

� Available Memory = Available Memory – Process Size

If a row exists

o Partitionnum=partitionnum+1

o Create a partition equal to the size of the program

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

19

o Update the Partition Table row with partition number,

partition size, process number, process number, process

size, and external fragment = 0

o Update the process table with partition number and size

and

o Allocated Flag =A

o Available Memory = Available Memory – Process Size

Process Step-5

o Print the process and table and the hole size

Process step-6

o This step is done in a LOOP till user wants to exist

o Input 1 +continue, 2= stop

If 2 Break

Read the size of New Program

o Processnum = processnum +1

o If available memory>Program Size

o Partitionnum = partitionnum +1

o Create a partition equal to the size of the program

o Update the table row with partition number, partition size,

process number, process size, and external fragment = 0

o Update the process table with partition number and size

and Allocated Flag = A

o Available a memory = Available Memory – Process size

If available memory< Program Size

o Find the process row entry, which leads to least External

Fragmentation

o External Fragmentation = Partition size – current program size

o Update the partition Table row related to process selected, with

process number, process size, and external table with partition

number and Allocated Flag=A

o Print process table and partition Table

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

20

4) Simulate all File Organization techniques:

a) Single level Directory b)Two level Directory c) Hierarchical d) DAG

File Organization Techniques

Directory Structure :

The file system of computer can be extensive some systems store thousands of

files on hundreds of giga bytes of disk to manage all these data. We need to

organize them. This organization is usually done in two ports. First the file

system is broken into partition. Each disk on system contains at least one

partition, which is a low level structure in which files and directories reside. Each

partition is treated as a separate storage device; where as other systems allow

partitions to be larger than a disk to group disks into one logical structure. In this

way, the user needs to be concerned with only the logical directory and file

structure.

Second, each partition contains information about files within it. This information

is kept in entries in a device directory or volume of table contents. The device

directory records information such as name location size and type for all files on

that partition.

The most common schemes for defining the logical structure of a directory.

Single – level directory

The simplest directory structure is the single level directory. All files are

contained in the same directory, which is easy to support and understand.

Directory

Cat Log A Test Data Mail Cont Record

Files Single-level directory

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

21

Two – level directory

The major disadvantage to a single-level directory is the confusion of file names

between different users. The standard solution is to create a separate directory for

each user.

In the two-level directory structure, each user has his own user file directory

(UFD). Each UFD has a similar structure but lists only the files of a single user.

User1 User2 User3 User3

Cat Do A Test A Data A Test X Data a

Tree – Structured directories

A two – level directory is viewed as a two – level tree. The natural generalization

is to extend the directory structure to a tree of arbitrary height. This

generalization allows users to create their own sub directories and to organize

their files accordingly a tree in the most common directory structure. The tree has

root directory, every file on the system has a unique path name.

Start Mail First Final Count Hex P E mail

Spell Bin programme

User file

directory

Master file directory

Two level directory structure

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

22

Cat Do A Test Record List final

5) Simulate Banker’s Algorithm for Deadlock Avoidance.

DEAD LOCK AVOIDANCE

Methods for Handling Deadlock

• Never let deadlock occur

• Prevention: break one of the 4 condition

• Avoidance: resources give advance notice of maximum use

• Let deadlock occur and do something about it

• Detection: search for cycles periodically

• Recovery: preempt process or resources

• Don’t worry about it(UNIX and other OS)

• Cheap: just reboot (it happens rarely)

Deadlock: Avoidance

• Process give advance notice maximum usage of resources

• Process make actual request when they need a resource

• Avoidance algorithm: allocate request only if it yields a safe state

• Conceptually the process could be run in this order

deadlock

safe

unsafe

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

23

Banker’s Algorithm

• Multiple instances of resource types IMPLIES cannot use resource

allocation graph

• Banks do not allocate cash unless they can satisfy customer needs when a

new process enters the system

• Declare in advance maximum need for each resource type

• Cannot exceed the total resources of the type

• Later, process make actual request for some resources

• Otherwise, suspend process until other process release enough resources

Banker: Example

Initially:

Available

A B C

10 5 7

Later snapshot:

Max - Allocation = Need

Available

A B C A B C A B C A B C

P0 7 5 3 0 1 0 7 4 3 3 3 2

P1 3 2 2 2 0 0 1 2 2

P2 9 0 2 3 0 2 6 0 0

P3 2 2 2 2 1 1 0 1 1

P4 4 3 3 0 0 2 4 3 1

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

24

Safety Algorithm

STEP 1:initialize

Work :=Available;

For I = 1,2……….n

Finish[i] = false

STEP 2: find I such that both

a. finish[i] is false

b. need I <=work if no such I, goto STEP 4

STEP 3:

Work := work+ allocation i

Finish [i] =true

Goto STEP 2

STEP 4:

If finish[i] = true for all I, system is in safe state

Banker: Safety Example

Using the previous Example, P1, P2, P3, P4,P0 satisfies criteria

Max - Allocation = need <=

work

Available

A B C A B C A B C

A B C

P1 3 2 2 2 0 0 1 2 2 3 3 2

3 3 2

P3 2 2 2 2 1 1 0 1 1 5 3 2

P4 4 3 3 0 0 2 4 3 1 7 4 3

P2 9 0 2 3 0 2 6 0 0 7 4 5

P0 7 5 3 0 1 0 7 4 3 10 4 7

10 5

7<<<initial system

Resources request Algorithm:

Say P1 request (1, 0, 2)

Compare to Need 1: (1,0, 2) <=(1, 2, 2)

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

25

Compare to available: (1, 0,2) <= (3, 3, 2)

Pretend to allocate resources:

Max - Allocation = Need

Available

A B C A B C A B C

P0 7 5 3 010 7 4 3 2 3

0<<<

P1 3 2 2 3 0 2<<< 0 2 0<<<

P2 9 0 2 3 0 2 6 0 0

P3 2 2 2 2 1 1 0 1 1

P4 4 3 3 0 0 2 4 3 1

Is this safe? Yes: P1, P3, P4, P0, P2

Can P4 get (3, 3, 0)? No,(3,3,0) > (2, 3, 0) Available

Can P0 get (0, 2, 0)? (0,2, 0) < (2,3, 0) Available

Pretend: Available goes to (2, 1. 0)

But All needs greater than Available than Available IMPLIES NOT SAFE

Expected Output :

enter the no of processes::4

enter the max types of resources::3

enter the claim for the processes::

enter the allocation for the processes::

P1 P2 P3 P4 P1 P2 P3 P4

R1 3 6 3 4 R1 1 6 2 0

R2 2 1 1 2 R2 0 1 1 0

R3 2 3 4 2 R3 0 2 1 2

enter the resource vector::

9

3

6

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

26

enter the available vector::

0

1

1

the system is in a safe state

6) Simulate Bankers Algorithm for Deadlock prevention.

Deadlock: Prevention

• Break mutual exclusion:

• Read-only files are shareable

• But some resources

• Are intrinsically non-shareable (printers)

• Break hold and wait:

• Request all resources in advance

• Request (tape, disk, printer)

• Release all resources before requesting New batch

• Request (tape, disk), release (tape, disk), request (disk, printer)

• Disadvantages: low resources utilization, starvation

Deadlock: Prevention

• Break no preemption

• Process 1 request resources already allocated to process

• process I forfeits its current resources

• if process 2 is waiting for other resources: process 2 forfeits

• used for resources whose state is easily saved / restored

• CPU registers and memory space

• Break circular wait

• Process request resources in increasing

• Order

Expected Output :

enter the no of processes::4

enter the max types of resources::3

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

27

enter the claim matrix and allocation matrix::

P1 P2 P3 P4 P1 P2 P3 P4

R1 3 6 3 4 R1 1 6 2 0

R2 2 1 1 2 R2 0 1 1 0

R3 2 3 4 2 R3 0 2 1 2

enter the resource vector::

9

3

6

enter the available vector::

0

1

1

the process p1 claims resources within system limit

the allocated resources are within claim limit

the process p2 claims resources within system limit

the allocated resources are within claim limit

the process p3 claims resources within system limit

the allocated resources are within claim limit

the process p4 claims resources within system limit

the allocated resources are within claim limit

No error in count of resources r1

No error in count of resources r2

No error in count of resources r3

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

28

7) Simulate all page replacement algorithms:

a) FIFO b) LRU c) LFU

Page Replacement Algorithms

FIFO algorithm:

The simpler page replacement algorithm is a FIFO algorithm. A FIFO

replacement algorithm associates with each page the time when that page was

brought into memory. When a page must be replace, the oldest page is chosen.

We can create a FIFO queue to hold all pages in memory. We replace the page at

the head of the queue when a page is brought into memory; we insert it at the tail

of the queue.

7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1

7 7 7 2 2 2 4 4 4 0 0 0 7 7 7

0 0 0 3 3 3 2 2 2 1 1 1 0 0

1 1 4 0 0 0 3 3 3 2 2 2 1

LFU algorithm:

The least frequently used (LFU) page replacement algorithm requires that the

page with the smallest count be replaced. The reason for this selection is that an

actively used page should have a large reference occurs.

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net

29

8) Simulate Paging Technique of memory management

PAGING

Logical address space of a process can be

noncontiguous; process is allocated physical memory

whenever the latter is available

Divide physical memory into fixed-sized blocks called frames

(size is power of 2, between 512 bytes and 8,192

bytes)

Divide logical memory into blocks of same size called pages

Keep track of all free frames

To run a program of size n pages, need to find n free

frames and load program

Set up a page table to translate logical to physical addresses

Internal fragmentation

www.jntuworld.com

www.jntuworld.com

www.jwjobs.net