Top Banner
SS Lab Programs 6 th sem PART A LEX and YACC Programs Execute the following programs using LEX: 1) a. Program to count the number of characters, words, spaces and lines in a given input file. b. Program to count the numbers of comment lines in a given C program.Also eliminate them and copy the resulting program into separate file. 2) a. Program to recognize a valid arithmetic expression and to recognize the Identifiers and operators present. Print them separately. b. Program to recognize whether a given sentence is simple or Compound. 3) Program to recognize and count the number of identifiers in a given Input file. Execute the following programs using YACC: 4) a. Program to recognize a valid arithmetic expression that uses Operators +, -, * and /. b. Program to recognize a valid variable, which starts with a letter, followed by any number of letters or digits. 5) a. Program to evaluate an arithmetic expression involving operators +, - , * and /. b. Program to recognize strings ‘aaab’, ‘abbb’, ‘ab’ and ‘a’ using the grammar (anbn, n>= 0). 6) Program to recognize the grammar (anb, n>= 10). PART B Unix Programming: 1. a) Non-recursive shell script that accepts any number of arguments and prints them in the ISE Dept. BNMIT,Bangalore -1-
40
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: SSLABMannual

SS Lab Programs 6th semPART A

LEX and YACC Programs

Execute the following programs using LEX:

1) a. Program to count the number of characters, words, spaces and lines in a given input file. b. Program to count the numbers of comment lines in a given C program.Also eliminate them and copy the resulting program into separate file.

2) a. Program to recognize a valid arithmetic expression and to recognize the Identifiers and operators present. Print them separately. b. Program to recognize whether a given sentence is simple or Compound.

3) Program to recognize and count the number of identifiers in a given Input file.

Execute the following programs using YACC:

4) a. Program to recognize a valid arithmetic expression that uses Operators +, -, * and /. b. Program to recognize a valid variable, which starts with a letter, followed by any number of letters or digits.

5) a. Program to evaluate an arithmetic expression involving operators +, - , * and /. b. Program to recognize strings ‘aaab’, ‘abbb’, ‘ab’ and ‘a’ using the grammar (anbn, n>= 0).

6) Program to recognize the grammar (anb, n>= 10).

PART B

Unix Programming:

1. a) Non-recursive shell script that accepts any number of arguments and prints them in the Reverse order, ( For example, if the script is named rargs, then executing rargs A B C should produce C B A on the standard output).b) C program that creates a child process to read commands from the standard input and execute them (a minimal implementation of a shell – like program). You can assume that no arguments will be passed to the commands to be executed.

2. a) Shell script that accepts two file names as arguments, checks if the permissions for these files are identical and if the permissions are identical, outputs the common permissions, otherwise outputs each file name followed by its permissions. b) C program to create a file with 16 bytes of arbitrary data from the beginning and another 16 bytes of arbitrary data from an offset of 48. Display the file contents to demonstrate how the hole in file is handled.

3. a) Shell function that takes a valid directory names as an argument and recursively descends all the subdirectories, finds the maximum lengths of any file in that hierarchy and writes this maximum value to the standard output. b) C program that accepts valid file names as command line arguments and for each of the arguments, prints the type of the file ( Regular file, Directory file, Character special file, Block special file, Symbolic link etc.)

ISE Dept. BNMIT,Bangalore-1-

Page 2: SSLABMannual

SS Lab Programs 6th sem

4. a) Shell script that accepts file names specified as arguments and creates a shell script that contains this file as well as the code to recreate these files. Thus if the script generated by your script is executed, it would recreate the original files(This is same as the “bundle” script described by Brain W. Kernighan and Rob Pike in “ The Unix Programming Environment”, Prentice – Hall India). b) C program to do the following: Using fork( ) create a child process. The child process prints its own process-id and id of its parent and then exits. The parent process waits for its child to finish (by executing the wait( )) and prints its own process-id and the id of its child process and then exits.

5. a) Shell script that accepts path names and creates all the components in that pathnames as directories. For example, if the script name is mpe, then the command mpe a/b/c/d should create directories a, a/b, a/b/c, and a/b/c/d. b) C program that accepts one command-line argument, executes the arguments as a shell command, determines the time taken by it and prints the time values, Use the “times”, function and the “tms” structure. The code need not include error checking.

6. a) Shell script that accepts valid log-in names as arguments and prints their corresponding home directories. If no arguments are specified, print a suitable error message. b) C program that accepts a valid directory names as a command line argument and lists all the files in the given directory as well as all the subsequent subdirectories. (The solution can be recursive or non-recursive).

7. a) Shell script to implement terminal locking. It should prompt the user for a password. After accepting the password entered by the user, it must prompt again for password confirmation ( to retype the password). If a match occurs, it must lock the terminal and prompt for the password. If the proper password is entered, the terminal must be unlocked. Note the script must be written to disregard BREAK, Control-D etc. No time limit need be implemented for the lock duration. b) C program to prompt the user for the name of an environment variable and print its value if it is defined and a suitable message otherwise; and to repeat the process if user wants it.

Instructions:In the examination, a combination of one LEX and one YACC problem has to be asked from Part A for a total of 30 marks and one programming exercise from Part B has to be asked for a total of 20 marks.

ISE Dept. BNMIT,Bangalore-2-

Page 3: SSLABMannual

SS Lab Programs 6th sem

Lex and Yacc

Two LPDT's ( Language Processor Development Tools) widely used in generation of Compilers are Lexical Analyzer Generator (LEX )and the Parser Generator (YACC).

LEX

LEX is a tool for automatic generation of lexical analyzer. A Lexical analyzer is the first phase of a compiler. A LA scans the input text character by character & recognize tokens such as identifiers, constants etc.Lex is generally used in the manner depicted in figure.

Lex source program lex.yy.c

filename.l

lex.yy.c a.out

Input Stream Sequence of token

Fig: Creating a Lexical Analyzer with Lex

First a specification of lexical analyzer is prepared by creating a program filename.l in the lex language. then filename.l is run through the lex compiler to produce a C program lex.yy.c.

The program lex.yy.c consists of a tabular representation of a transition diagram constructed from regular expression of filename.l & actions associated with regular expression in filename.l are carried over directly to lex.yy.c

Finally, lex.yy.c is run through C compiler to produce an object code a.out which is the lexical analyzer that transforms an input stream into a sequence of tokens.

Structure of Lex program

Input the lex consists of three section/parts

Declaration Section%%Rules Section%%User Subroutines Section

ISE Dept. BNMIT,Bangalore-3-

Lex Compiler

C compiler

a.out

Page 4: SSLABMannual

SS Lab Programs 6th sem

1. Declaration Section :It includes the literal block, definitions, start conditions.

i. Literal block: a C code bracketed by the lines %{ C code, declarations %}

ii. Definition: allow us to give name to all or part of a RE(regular expression) that can be referred by name in the rules section. eg. it defines the symbol 'letter' to stand for any upper or lower case letter and symbol 'digit' to stand for any digit.

2. Rules Section : Contains pattern lines and C code. Pattern is written using RE and C code, also called the action part acts according to the pattern specified. If C code exceeds one line, then it must be enclosed in braces { }.it is of the form:P1 {action1}P2 {action2}. .. .Pn {actionn}

where each Pi is a regular exprssion (pattern specification or string specification)each actioni is a C-laguage statementsThese are enclosed between %% and %%Eg; lex {printf(“\nThis is lex lab”);}The meaning of the above rule is that every occurance of 'lex ' is replaced by ' This is lex lab'.

3. User Subroutine Section: This section includes routines called from the rules.

main(){yylex(); /*lexer or scanner*/}

Lex specifications are set of patterns, that is pattern part of the rules section, in which Lex matches against the input. Each time one of the patterns matches, the Lex program invokes C code, that is the action part of rules section, which takes some action with the matched token.

Lex translates the lex specifications into a file containing C routine called yylex().The yylex() will recognize expressions in a stream and perform the specified actions for each expression as it is detected.

The pattern part of rules section is written using Regular Expressions (REs)RE is a pattern description using a meta language. REs are composed of normal characters and meta characters.

The characters/Meta characters that form regular expression along with their descriptions are listed below:

ISE Dept. BNMIT,Bangalore-4-

Page 5: SSLABMannual

SS Lab Programs 6th sem. Matches any single character except the new line character “\n”[] Matches any one of the characters within brackets. Also called as character class. If the first character is circumflex “^”, it changes the meaning to match any character except those within the brackets. A range of characters is indicated with ‘-‘.

Example:1. [a-z0-9] indicates the character class containing all the lower case letters, and

the digits.2. [^ask] matches all characters except a,s, and k

* Matches zero or more of the preceding expression.

Ex: [A-Za-z][A-za-z0-9]* => ap90,a1, z23, w…. indicates all alphanumeric strings with a leading alphabetic character. This is a typical expression for recognizing identifiers in computer language.

+ Matches one or more of the preceding expression Ex: a+ => a, aa, aaa…. [a-z]+ is all strings of lower case letters. [ab]+ => ab, abab, ababab…..

? The operator ? indictes an option element of an expression Ex: ab?c matches either ac or abc. i.e., matches zero or one occurrence of the preceding RE ,here b is optional.

$ If the very last character is $, the expression will only be matched at the end of a line. i.e., matches the end of line as the last character of RE. Ex:ab$ matches any stream that ends with b.

{} Specify either repetitions (if the enclose numbers) or definition expansion (if the enclose a name). Ex: {digit} looks for a predefined string named digit and inserts it at that point in the expression. A{1,5} matches looks for 1 to 5 occurrences of a. i.e., indicates how many times the previous RE is allowed to match when containing one or two numbers.

| Indicates alternation Ex: (ab|cd) matches either ab or cd. i.e., matches either the preceding RE or the following RE.

() Groups a series of REs together into a new RE. (ab|cd+)?(ef)* matches such strings abefef, efef, cdef, cddd.

“..” Interprets everything within the quotation marks literally. Meta characters other than C escape sequence lose their meaning. Ex:”/*” matches the two characters * & /.

^ As the first character of RE, it matches the beginning of a line. Also used for negation within [].

\ used to escape meta characters. If the following character is a lower case letter, then it is a C escape sequence such as \t,\n etc.,

ISE Dept. BNMIT,Bangalore-5-

Page 6: SSLABMannual

SS Lab Programs 6th sem

/ Matches the preceding RE but only if followed by the following RE. Ex:0/1 matches ‘0’ in the string ‘01’ but does not match anything in the string ‘0’or ‘02’. Only one slash is permitted per pattern.<> A name or list of names in angle brackets at the beginning of a pattern makes that

pattern apply only in the the given start states.

Commands to compile and execute lex programs:

Lex programs has to be stored with filename.l extension, then there are two steps in

compiling the lex program.

1. The Lex source must be turned into generated program in the host general purpose language. i.e., C language, using the command

$lex filename.l

This lex compiler generates a C file called lex.yy.c, the literal block, action part of rules section, and user subroutine section of lex program where C valid statements will be included gets copied as it is to this C file lex.yy.c. This C file contains the lexer, yylex().When lex scanner runs, it matches the input against the patterns in the rules section.Every time it finds a match, it executes the C code associated with the pattern.When no match, lex writes a copy of the token to the output. Lex executes action for the longest possible match for the current input.

2. This C file will be compiled using C compiler and loaded, usually with a library of lex subroutines. command for compiling this is

$cc lex.yy.c –ll

where –ll is the loader flag access the lex library.

The resulting program is placed on the usual file a.out for later execution.

3. $ a.out argument list if any

ISE Dept. BNMIT,Bangalore-6-

Page 7: SSLABMannual

SS Lab Programs 6th sem

YACC (Yet Another Compiler Compiler)

Yacc provides a general tool for imposing structure on the input to a computer program. Figure shows a schematic diagram of a parser generated by YACC.

Yacc Specifications y.tab.c filename.y

y.tab.c a.out

Sequence of tokens parse tree

Input to the yacc is a specification of syntax analysis construct of a Language L prepared by creating a program filename.y. Then this file is run through the C compiler to produce a C program y.tab.c Finally y.tab.c is run through C Compiler to produce the object code, which is the parser which transforms sequence of tokens into some representation of parse tree.Figure shows a schematic for developing the analysis phase of a compiler for language L using Lex & Yacc.

Lex Specification

Syntax specificationof Language L

IR / Target codeStructure of Yacc program

Declaration section%%Rules section%%User subroutine section

ISE Dept. BNMIT,Bangalore-7-

Yacc Compiler

C Compiler

a.out

Lex Compiler Scanner

ParserYacc Compiler

Page 8: SSLABMannual

SS Lab Programs 6th sem

Declaration/Definition section:

. Includes declarations of the tokens used in the grammar. It can also include a literal block, C code enclosed in %{

%}. Token definitions and specification of associativity and precedence.

Eg. %token PLUS, MINUS Rules section:. Contains the grammar rules and actions containing C code.· The parser generated by yacc performs reductions according to this grammar.· The action associated with a grammar are executed when a reduction is made according to the

grammar. Each rule starts with a non-terminal symbol and a colon followed by a possibly empty list of symbols or tokens and actions.

Eg. e: e PLUS e {$$=$1+$2;}· yacc provides predefined variables($$, $1, $2,.......)· A symbol '$n' in the action part of the grammar rule refers to the attribute of the nth symbol in

the RHS of the grammar. '$$' represents the attribute of the LHS symbol of grammar.

User Subroutine section:. Yacc copies the contents of this section verbatim to the C file.. Typically includes routines called from the actions.main(){yyparse() /* parser*/}

Compiling and executing Yacc programs:

Yacc programs must be stored as filename.y Extension.

1. First lex program must be compiled as usual which generates the C file lex.yy.c

$lex filename.l

2. Then Yacc program must be compiled which generates the C file called y.tab.c.

$yacc -d filename.y

This yacc compiler generates a C file called y.tab.c, the literal block, action part of rules section, and user subroutine section of Yacc program where C valid statements will be

included gets copied as it is to this C file y.tab.c. This C file contains the parser, yyparse().When Yacc parser runs, it in turn repeatedly calls yylex, the lexical analyzer which supplies tokens to yacc as and when required. When an error is detected, parse returns the

ISE Dept. BNMIT,Bangalore-8-

Page 9: SSLABMannual

SS Lab Programs 6th semvalue 1, or the lexical analyzer returns the end marker token and the parser accepts. In this case, yyparse returns the value 0.

3. Now both C files will be compiled using C compiler.

$cc lex.yy.c y.tab.c –ll -ly

This C files will be compiled using C compiler and loaded, usually with a library of yacc and lex subroutines. –ly is the loader flag access the Yacc library.

4. The resulting program is placed on the usual file a.out for later execution. To terminate, press Cntrl+d.

$ ./a.out

i. Special directives and Library routines:

1. yylex() : The scanner/lexer created b Lex has the entry point yylex().It scans the program. All code in the rules section is copied into yylex().

2. yytext : Whenever the lexer matches a token, the text of the token is stored in the null terminated string yytext. It is array of characters whose contents are replaced each time new token is matched.

3. yywrap : => When a lexer encounters an end of file, it calls the routine yywrap() to find out what to do next. If yywrap() returns 0, the scanner continues scanning, if it returns 1, the scanner returns zero token to report end of file.

4. Echo : Writes the token to the current output file yyout. Equivalent to fprintf(yyout,”%s”,yytext);

5. input() : Provides character to the lexer. Also yyinput()

6. yyleng => Stores the length of yytext. Same as strlen(yytext).

7. yyparse() => The entry point to the yacc generated parser. Returns zero on success and non-zero on failure.

8. yyerror() : Simple error reporting routine, yyerror(char *msg).

9. % : Used to declare the definitions like %token, %start, %type, %left, %right, %union.

10. $ => Introduces a value of reference in actions. Ex: $3 refers the value of third symbol in the RHS of the rule, c=12+89, $3 refers to value 89.

11. ‘ => Used to define literal tokens Ex: ‘+’, ‘-‘,…

12 ; => Each rule in the rule section end with a semicolon.

12. | => To specify the alternative RHS for the same LHS in a rule. Ex: e : e’+’e|e’-‘e|e’*’e.

ISE Dept. BNMIT,Bangalore-9-

Page 10: SSLABMannual

SS Lab Programs 6th sem

13 : => Used to separate LHS and RHS of a rule.

14. %token => Are the symbols that the lexer passes to the parser. So parser need to call yylex() which returns the tokens required by the parser. All tokens must be explicitly defined in the definition section.16. %left, %right, %nonassoc => Explicit means of specifying left, right, and no

associativity.

17. %start <rule name> => Specifies the first rule that the parser should start.

18. %prec => Changes the precedence level associated with a particular grammar rule. Ex: unary minus may be given highest level of precedence, whereas binary minus will have lower level precedence.

19. %s or %x => Indicates start condition.

ISE Dept. BNMIT,Bangalore-10-

Page 11: SSLABMannual

SS Lab Programs 6th semPart – A Lex Programs

1a. Lex Program to count the number of characters, words, lines, and blanks in a given

input file

%{int c_count=0,l_count=0, w_count=0,b_count=0;

%}word [^ \t\n]+eol \n%%[ ] {b_count++; c_count++;}{word} {w_count++; c_count+=yyleng;}{eol} l_count++;. ECHO;%%main(int argc, char *argv[]){FILE *file;if(argc > 1){file=fopen(argv[1],"r");if(!file){printf("could not open file");exit(1);}yyin=file;yylex();printf("The Number of Characters=%d\n",c_count);printf("The Number of Words=%d\n",w_count);printf("The Number of Lines=%d\n",l_count);printf("The Number of Blanks=%d\n",b_count);}elseprintf("usage:argv[0] argv[1]"); }Sample input/output

$ ./a.out infile.txt

The Number of Characters=64The Number of Words=12The Number of Lines=3The Number of Blanks=10

Contents of file infile.txt:This is System programming Labwe are doing lex and yacc programs

ISE Dept. BNMIT,Bangalore-11-

Page 12: SSLABMannual

SS Lab Programs 6th sem

1b. Program to count the number of comment lines in a given C program. Also

eliminate them and copy that program into a separate file.

%{int comments = 0;%}%%[\t]*"/*".*"*/"[ \t\n]* { comments++;}. {fprintf(yyout,yytext);}%%main(int argc,char *argv[]){FILE *fin, *fout;

if(argc>2){fin=fopen(argv[1],"r");fout=fopen(argv[2],"w");if(!fin){printf("Could not open the file");exit(1);}yyin=fin;yyout=fout;yylex();printf("the numebr of comments are=%d",comments);}elseprintf("Usage: argv[0] argv[1] argv[2]");}Sample input/ouput$ ./a.out cprog.c result.cthe number of comments are=3Contents of cprog.c /* comment section */ main() /* main() function */ {int a; /* declaration section */}result.cmain(){int a;}

2a. program to recognize a valid arithmetic expression and identify the identifiers and

ISE Dept. BNMIT,Bangalore-12-

Page 13: SSLABMannual

SS Lab Programs 6th semoperators present. Print them separately.

%{int top=-1,id=0,pls=0,min=0,mul=0,di=0,oper=0,v=1,d[100],i=0,j=0,k=0,h=0,m=0;char stk[100],c[100],ope[100];%}iden [a-zA-Z]+[a-zA-Z0-9]*dig [0-9]*%%{dig} {id++;d[i++]=atoi(yytext);h++;}{iden} {id++;if(yyleng>1) {for(m=0;m<yyleng;m++)

c[j++]=yytext[m]; c[j++]='\n'; } else { c[j++]=yytext[0]; c[j++]='\n'; }; }"+" {pls++;oper++;ope[k++]=yytext[0];ope[k++]='\n';}"-" {min++;oper++;ope[k++]=yytext[0];ope[k++]='\n';}"*" {mul++;oper++;ope[k++]=yytext[0];ope[k++]='\n';}"/" {di++;oper++;ope[k++]=yytext[0];ope[k++]='\n';}"(" {stk[++top]='(';}")" {if(stk[top--]!='(') v=0;}%%main( ){yylex();if(top==-1&&v==1&&id==oper+1){printf("The Given Arithmetic Expression Is Valid \n");printf(" The Individual Operators Count Is:\n");printf("Plus=%d \t Minus=%d \t Multiply=%d \t Division=%d\n",pls,min,mul,di);printf("The Identifiers Are:\n");if(h>0) { for(m=0;m<h;m++)printf("%d\t",d[m]);}printf("%s\n",c);printf("The Operators Are:\n");printf("%s\n",ope); } elseprintf("Invalid Arithmetic Expression\n");}

ISE Dept. BNMIT,Bangalore-13-

Page 14: SSLABMannual

SS Lab Programs 6th semSample input/output$ ./a.out (a+d)-d*gThe Given Arithmetic Expression Is Valid The Individual Operators Count Is:Plus=1 Minus=1 Multiply=1 Division=0The Identifiers Are:addgThe Operators Are:+-*

2b. Program to recognize whether a given sentence is simple or compound.

%{int flag =0;

%}%%(" "[aA][nN][dD]" ")|(" "[oO][rR]" ")|(" "[bB][uU][tT]" ") flag=1;%%main(){

yylex();if(flag)

printf("\n Compound Sentence");else

printf("\n Simple sentence");}Sample input/output$ ./a.outRam and SitaCompound Sentence$ ./a.outI am an IndianSimple Sentence

3. Lex Program to recognize & count the number of identifiers in a given input file

ISE Dept. BNMIT,Bangalore-14-

Page 15: SSLABMannual

SS Lab Programs 6th sem%{

int idc=0;%}space [ \t\n]ID [a-zA-Z][a-zA-Z0-9]*DEC ({space}*"int"{space}+|{space}*"float"{space}+|{space}*"char"{space}+|{space}*"short"{space}+)%s DEF%%{DEC} {BEGIN DEF;}<DEF>{ID}\, idc++;<DEF>{ID}\; {idc++;BEGIN 0;}. ; %%main(int argc, char *argv[]){

FILE *f1;f1=fopen(argv[1],"r");if(!f1){

printf("File open error");exit(1);

}yyin=f1;yylex();printf("The numbers of identifiers are %d",idc);

}Sample Input/Output$ ./a.out infile.cThe numbers of identifiers are 3Contents of infile.cmain(){int a , b;float c;

}

YACC Programs

ISE Dept. BNMIT,Bangalore-15-

Page 16: SSLABMannual

SS Lab Programs 6th sem4a. Program to recognize a validity arithmetic expression that uses operators +, -, *, and / Lex program (say 4a.l)

%{#include "y.tab.h"

%}%%[0-9a-z]+ {return NUM;}[*+/] {return OPR;}[-] {return SUB ;}[\n] {return 0;}[\t] ;. {return yytext[0];}%%Yacc program (say 4a.y)%{int valid = 1;%}%token NUM OPR SUB%%statememt:expr expr: NUM

|SUB NUM| expr OPR NUM| expr SUB NUM| '(' expr ')'| expr OPR '(' expr ')'| expr '(' expr ')';

%%int yyerror(char *s){

valid = 0;}main(){

yyparse();if(valid)

printf("\n Valid expression");else

printf("\n Invalid Expression");}Sample input/output$ ./a.outa+bValid expression$ ./a.outnum1-num2Valid expression$ ./a.out1+2

ISE Dept. BNMIT,Bangalore-16-

Page 17: SSLABMannual

SS Lab Programs 6th semValid expression$ ./a.out(a+b)*f-h Valid expression

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

Lex program (say 4b.l)

%{#include "y.tab.h"

%}%%[_a-zA-Z]+ return letter;[0-9] return digit;[\n] return 0;. return 0;%%Yacc Program (say 4b.y)%{int valid = 1;%}%token letter digit%%statement:expr {valid=1;}expr:letter |expr letter |expr digit ; %%int yyerror(){

valid=0;printf("\n Invalid variable\n");

}main(){

yyparse();if(valid)

printf("\n Valid Variable");}Sample input/output$ ./a.outNum1Valid Variable$ ./a.out345 Invalid variable

5 a. Program to evaluate an arithmetic expression involving operators +, -, *, and /.

Lex Program (say 5a.l)

ISE Dept. BNMIT,Bangalore-17-

Page 18: SSLABMannual

SS Lab Programs 6th sem%{#include "y.tab.h"extern int yylval;%}%%[0-9]+ { yylval = atoi(yytext); return NUM;}[\t] ;[\n] return 0;. return yytext[0];%%Yacc Program (say 5a.y)%{int valid = 1;%}%token NUM%left '+','-'%left '*','/'%left UMINUS%%exp:NUM {$$=$1;yylval=$$;} |exp '+' exp {$$ = $1+$3; yylval = $$ ;} |exp '-' exp {$$ = $1-$3; yylval = $$;} |exp '*' exp{$$ = $1*$3; yylval = $$;} |exp '/' exp { if($3==0)valid = 0;

else{$$=$1/$3; yylval = $$;}

} | '(' exp ')' {$$ = $2; yylval=$$;} | '-'exp %prec UMINUS { $$= -$2; yylval = $$;} ;%%int yyerror(){

valid = 0;}main(){

yyparse();if(valid)

{printf("\n Valid Expression\n");printf("Result = %d",yylval);

}else

printf("\n Invalid Expression"); }

Sample input/output$ ./a.out1+2

ISE Dept. BNMIT,Bangalore-18-

Page 19: SSLABMannual

SS Lab Programs 6th semValid ExpressionResult = 3$ ./a.out-4-7Valid ExpressionResult = -11

5b. Yacc Program to recognize strings 'aaabbb', 'aabb' and 'ab' using the grammar { anbn where n>0 }

Lex Program (say 5b.l)

%{#include "y.tab.h"%}%%[a] return A;[b] return B;[\n] return 0;. return 0;%%Yacc Program (say 5b.y)%{int valid =1;%}%token A B%%start:expr|line;expr:A expr B|A Bline: ;%%yyerror(char *s){

printf("\n Invalid grammar");valid = 0;

}int main(){

yyparse();if(valid)

printf("\n Valid grammar"); }

Sample input/output$ ./a.outaabbValid grammar$ ./a.outabbInvalid grammar

ISE Dept. BNMIT,Bangalore-19-

Page 20: SSLABMannual

SS Lab Programs 6th sem6. Program to recognize the grammar anb where n>=0. Lex Program (say 6.l)

%{#include "y.tab.h"%}%%[a] return A;[b] return B;\n return 0;. return 0;%%Yacc Program (say 6.y)%{int valid =1;%}%token A B%%start:expr;expr:expr2 expr1 B | expr2 B;expr1:expr1 A|A;expr2:A A A A A A A A A A;%%int yyerror(char *s){

valid =0;}int main(){

yyparse();if(valid)

printf("\n Valid Grammar");else

printf("\n Invalid Grammar");}Sample input/output[root@localhost SPL]# ./a.outaabInvalid Grammar$ ./a.outaaaaaaaaaabValid Grammar

PART - B

1a. Write a non recursive shell script that accepts any number of arguments & prints them

ISE Dept. BNMIT,Bangalore-20-

Page 21: SSLABMannual

SS Lab Programs 6th sem in the reverse order.

if [ $# -eq 0 ] then echo “ No command line arguments\n” exit 0fiecho "I nput string is:$*"for x in "$@"doy=$x" "$ydoneecho "Reversed string is:$y"

Sample input/output

$ sh 1a.sh a b c dInput string is:a b c dReversed string is:d c b a

1b. Write a C program that creates a child process to read commands from standard input & execute them

#include<stdio.h>int main(){ char str[10]; int pid,i; pid=fork();if(pid==0){ printf("Child process..."); do { printf("\nEnter a command:"); scanf("%s",str); system(str); printf(“Enter 1: Continue 0:exit”); scanf(“%d”,&i); }while(i!=0); printf("child process has terminated\n");}else{

wait();printf("\nParent Process");

}return 0; }Sample input/output# ./a.outChild process...Enter a command:date

ISE Dept. BNMIT,Bangalore-21-

Page 22: SSLABMannual

SS Lab Programs 6th semWed Feb 7 21:52:00 IST 2007Enter 1: Continue 0:exit0child process has terminatedParent Process

2a. Write a shell script that accepts two filenames as arguments, checks if the permissions for these files are identical & if the permissions are identical, ouputs the common permissions, otherwise outputs each file names followed by its permissions

if [ $# -eq 0 ] then echo “ No command line arguments\n” exit 0fif1=`ls -l $1|cut -c2-10`f2=`ls -l $2|cut -c2-10`if [ $f1 == $f2 ]thenecho "files $1 & $2 have common file permissions: $f1"elseecho “File $1 and $2 have different permission”echo "file $1 has file permissions : $f1"echo "file $2 has file permissions : $f2"fi

Sample input/output$ sh 2a.sh 4a.l 4a.shfile 4a.l has file permissions : rw-r--r--file 4a.sh has file permissions : rwxr-xr-x# sh 2a.sh 1a.sh 1b.cfiles 1a.sh & 1b.c have common file permissions: rwxr-xr-x

2b. Write a C program to create a file with 16 bytes of arbitrary data fro the beginning and another 16 bytes of arbitrary data from an offset of 48.Didplay the file contents to demonstrate how the hole in file is handled.

#include<sys/types.h>#include<stdlib.h>#include<sys/stat.h>#include<fcntl.h>#include<stdio.h>#include<unistd.h>int main(){

char buf1[]="123456789ABCDEFG";char buf2[]="HIJKLMNOPQRSTUVW";int fd;fd=creat("t.txt",O_WRONLY);write(fd,buf1,16);lseek(fd,48,SEEK_SET);

ISE Dept. BNMIT,Bangalore-22-

Page 23: SSLABMannual

SS Lab Programs 6th semwrite(fd,buf2,16);printf(“ the contents of the file are\n”);system(“vi t.txt”);exit(0);

}Sample input/output$ ./a.out$t.txt file looks as123456789ABCDEFG^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@HIJKLMNOPQRSTUVW

3a. Shell script that takes a valid directory names as an argument and recursively descents all the subdirectories finds the maximum length of any file in that hierarchy and writes this maximum value to the standard output.

if [ $# -ne 1 ]thenecho "Usage : $0 directory"exit 1fils -Rl $1 | grep "^-" | sort -n -k 5,9 | tee f1echo "maximum length of file is "tail -1 f1 | cut -c 36-65

Sample input/output

$ sh 3a.sh .-rw-r--r-- 1 root root 76 Feb 7 21:43 y.tab.h-rw-r--r-- 1 root root 90 Feb 7 20:37 cprog.c-rw-r--r-- 1 root root 120 Feb 6 22:59 6.l-rw-r--r-- 1 root root 130 Feb 6 22:33 5b.l-rw-r--r-- 1 root root 152 Feb 6 23:15 4b.l-rw-r--r-- 1 root root 176 Feb 6 22:18 5a.lmaximum length of file is176 7 22:10 5a.l

3b. Write a C Program that accepts valid file names as command line arguments & for each of the arguments, prints the type of the file (Regular file,Directory file,Character device file etc)

#include <sys/stat.h>

ISE Dept. BNMIT,Bangalore-23-

Page 24: SSLABMannual

SS Lab Programs 6th sem#include<unistd.h>#include<stdio.h>int main(int argc,char * argv[]){ int i; struct stat file; for(i=1;i<argc;i++) {

if(lstat(argv[i],&file)!=0){ printf("File %s does not exits",argv[i]); continue; }printf("\nFile %s is a ",argv[i]);if(S_ISREG(file.st_mode)) printf("Regular File");else if(S_ISDIR(file.st_mode)) printf("Directory File");else if(S_ISCHR(file.st_mode)) printf("Character Device File");else if(S_ISBLK(file.st_mode)) printf("Block Device File");else if(S_ISFIFO(file.st_mode)) printf("FIFO File");#ifdef S_IFLINKelse if(S_ISLINK(file.st_mode)) printf("Symbolic Link File");#endif

} }

Sample input/output$ ./a.out 3a.shFile 3a.sh is a Regular File$ ./a.out 3a.sh /dev/hda4File /dev/hda4 is a Block Device File

4a. shell script that accepts file name specified as arguments & creates a shell script that contains this file as well as the code to recreate these files. Thus if the script generated by your script is executed it would recreate the original files

for x in $*doecho "cat > $x << ENDMabcdefghiENDM"done > recreate

Sample input/output

$ sh 7a.sh file1 file2$ vi recreatecat > file1 << hereabcdefghihere

ISE Dept. BNMIT,Bangalore-24-

Page 25: SSLABMannual

SS Lab Programs 6th semcat > file2 << hereabcdefghihere$ sh recreate$ ls file1 file2 recreate$ cat file1abcdefghi$ cat file2abcdefghi

4b. write a C program to create child process. the child process prints its own process-id and id of its parent and then exits. the parent process waits for its child to finish & prints its own process id & the id of its child process and then exits.

#include<stdio.h>int main(){

char str[10];int pid;pid=fork();if(pid==0){

printf("Child process...");printf("\n\nChild PID : %d",getpid());printf("\nParent PID : %d",getppid());printf("\n\nFinished with child\n");

}else{

wait();printf("\nParent process");printf("\nPARENT PID : %d",getpid());printf("\nChild PID : %d",pid);

}return 0;

}

Sample input/output ./a.outChild process...Child PID : 4145Parent PID : 4144Finished with child

ISE Dept. BNMIT,Bangalore-25-

Page 26: SSLABMannual

SS Lab Programs 6th semParent processPARENT PID : 4144Child PID : 4145

5a. Shell script that accepts pathnames and creates all the components in that path names as directories. For example, if the script name is mpe, then the command mpe a/b/c/d should create directories a, a/b,a/b/c and a/b/c/d

if [ $# -eq 0 ]thenecho "Usage: $0 [dir]/[sub]...."exit 1fiIFS='/'for dirname in $*domkdir $dirnamecd $dirnamedone

Sample input/output$ sh 4a.sh a/b/c/d

5b. C program that accepts one command line argument, executes the argument as shell command. determines the time taken by it and print the time values

#include<time.h>#include<unistd.h>#include<sys/types.h>#include<sys/times.h>int main(int argc,char*argv[]){

clock_t start,finish;struct tms s,e;float time;float clktck=sysconf(_SC_CLK_TCK);start=times(&s);system(argv[1]);finish=times(&e);time=(finish-start)/clktck;printf("real time taken to execute command:%s is %f",argv[1],time);printf("\n user time %f",(s.tms_utime-e.tms_utime)/clktck);printf("\n system time %f",(s.tms_stime-e.tms_stime)/clktck);return 0; }

Sample input/output$. /a.out dateWed Feb 7 22:30:56 IST 2007real time taken to execute command: date is 0.020000 user time 0.000000 system time 0.000000

ISE Dept. BNMIT,Bangalore-26-

Page 27: SSLABMannual

SS Lab Programs 6th sem

6a. Shell script that accepts valid login names as arguments & prints their corresponding home directories. if no arguments are specified, print a suitable error message.

if [ $# -eq 0 ] then echo “ No command line arguments\n” exit 0fifor nam in "$@"do grep "^$nam" /etc/passwd > listif [ $? –eq 0 ] then echo “home directory of $nam is “ cut –d ":" -f 1,6 listelse echo “ \n $nam is improper login name”fidone

Sample input/ouput

$ sh 5a.sh root mysql abc Home directory of root is /rootHome directory of mysql is /var/lib/mysql abc is improper login name

6b. C program that accepts valid directory names as a command line argument and list all files in the given directory as well as subdirectories (implementation of ls –lR)

#include<stdio.h>#include<ftw.h>#include<unistd.h>int myfun (const char *pathname,const struct stat *statptr,int type);main(int argc,char *argv[]){

if(argc<2)printf("usage :%s,directory\n",argv[0]);elseexit(nftw(argv[1],myfun,0,0)); }

int myfun(const char *pathname,const struct stat*statptr,int type){

if(type==FTW_F)printf("\nfile:%s",pathname);if(type==FTW_D)printf("\ndirectory:%s",pathname);

ISE Dept. BNMIT,Bangalore-27-

Page 28: SSLABMannual

SS Lab Programs 6th semreturn 0;

}

Sample input/output$ ./a.out /root/SPLRecursively descending into /root/SPL directory DIR /root/SPL :SPLabManual.doc 10a.awk 1b.c file2 7a.sh f1 2b.c 3.l test2.c t1 8a.sh outfile.txt 6.l 3a.sfile1 4a.sh 6b.c result.c 5b.y out.txt 1b.l y.tab.h g1 5b.c 3a.sh~ 2a.sh g2 9b.pl 4a.ytest cprog.c 5b.l 1.sh 3b.c 2a.l~ recreate y.tab.c 2a.l test.c 4a.l 2b.l 8b.pl file3 a.out.txt t2 gsg 4b.y 5a.sh 10b.c a 7b.awk 9a.sh 4b.l lex.yy.c 5a.l 5a.y 1a.l 2a.l,v 6.y 1a.sh SPLabManual.sxw 4b.c infile.txt 6a.sh

7a. Write a shell script to implement terminal locking. It should prompt the user for a password. If a match occurs, it must lock the terminal & prompt for the password. If the proper password is entered, the terminal must be unlocked.

trap ' ' 1 2 3 8 12 15 18 20stty -echoecho enter the passwordread p1echo reenter the passwordread p2if [ “$p1” = $p2" ]thenecho terminal lockedecho to invoke reenter the passwordread p3while [ "$p3" != "$p1" ]doecho password entered is not matchingecho reenter the passwordread p3done echo terminal unlockedfistty sane

Sample input/output$ sh 6a.shenter the password gsgreenter the password gsgterminal lockedto invoke reenter the password gsgterminal unlocked

7b. C program to prompt the user for the name of an environment variable and print its

ISE Dept. BNMIT,Bangalore-28-

Page 29: SSLABMannual

SS Lab Programs 6th sem value if it’s defined and a suitable message otherwise and to repeat the process if user wants it.

#include<stdio.h>#include<stdlib.h>int main(void){

char envvar[10];char *value;int choice;

do {

printf("Enter the environment var:");scanf("%s",envvar);

value=getenv(envvar);if ( value!=NULL)printf("%s has the value :%s",envvar,value);elseprintf("%s is not defined");printf("\nDo u want to continue:");scanf("%d",&choice);

}while(choice);return 0;}

Sample input/output./a.outEnter the environment var:PWDPWD has the value :/root/SPLDo u want to continue: 0

VIVA Questions

Part –A

1. What is lex?

ISE Dept. BNMIT,Bangalore-29-

Page 30: SSLABMannual

SS Lab Programs 6th sem2. What is yacc?3. What are the different phases of complier?4. Define token. How they are recognized by the scanners?5. What are different data structures used by assembler?6. What are the functions of assembler?7. What is regular expression?8. What is grammer?9. Explain the structures of lex and yacc programs.10. What is loader? What are types of loaders?

Part-B

1. Explain the feature of Unix OS?2. Explain the different files in UNIX system?3. What is fork? Explain the fork() function ?4. Explain the difference between fork and vfork?5. Explain how system function works?6. Explain the structure stat?7. Explain stat , fstat, lstat functions?8. What is process? Explain the parent child relationship.9. Explain the getpid, getppid,getuid,geteuid, getgid, getegit functions ?10. What are the main functions of shell?11. What are the steps involved in creating child process?12. What are positional parameters?13. Explain different exec function in UNIX?14. What are environmental variables?15. What is $*,$#,$$,$_,$!16. Where do you use expr in shell scripts?17. What is here document?18. What is shell script? How it is different form c program?19. What do you mean by exit status of a command?20. Where do you use cut command?21. Differentiate head and tail?22. What is set command?23. What is the function of lseek ( ) ?24. Explain getenv function?25. Explain the usage of trap command?26. How can you change the file permissions?

ISE Dept. BNMIT,Bangalore-30-