Sunteți pe pagina 1din 35

SSLabPrograms PART A LEX and YACC Programs Execute the following programs using LEX:

6thsem

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. -1BNMIT,Bangalore

SSLabPrograms

6thsem

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.

-2-

BNMIT,Bangalore

SSLabPrograms

LexandYacc

6thsem

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. Lexsourceprogramlex.yy.c filename.l lex.yy.ca.out

InputStreamSequenceoftoken a.out

Fig:CreatingaLexicalAnalyzerwithLex Firstaspecificationoflexicalanalyzerispreparedbycreatingaprogramfilename.lin thelexlanguage.thenfilename.lisrunthroughthelexcompilertoproduceaCprogram lex.yy.c. Theprogramlex.yy.cconsistsofatabularrepresentationofatransitiondiagram constructedfromregularexpressionoffilename.l&actionsassociatedwithregularexpressionin filename.larecarriedoverdirectlytolex.yy.c Finally,lex.yy.cisrunthroughCcompilertoproduceanobjectcodea.outwhichisthe lexicalanalyzerthattransformsaninputstreamintoasequenceoftokens.

StructureofLexprogram
Inputthelexconsistsofthreesection/parts ISE Dept. -3BNMIT,Bangalore

SSLabPrograms Declaration Section %% RulesSection %% UserSubroutinesSection

6thsem

1. Declaration Section: It includes the literal block, definitions, start conditions. i. Literal block: a C code bracketed by the lines %{ Ccode,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 statements These 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) ISE Dept. -4BNMIT,Bangalore

SSLabPrograms 6thsem RE is a pattern description using a meta language. REs are composed of normal characters and meta characters. Thecharacters/Metacharactersthatformregularexpressionalongwiththeirdescriptions arelistedbelow: . [] 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 * & /. -5BNMIT,Bangalore

{}

| () ..

ISE Dept.

SSLabPrograms ^

6thsem

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., 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 0or 02. Only one slash is permitted per pattern. Anameorlistofnamesinanglebracketsatthebeginningofapatternmakesthat

\ / <>

patternapplyonlyinthethegivenstartstates.

Commandstocompileandexecutelexprograms:
Lexprogramshastobestoredwithfilename.lextension,thentherearetwostepsin compilingthelexprogram. 1. The Lex source must be turned into generated program in the host general purpose language.i.e.,Clanguage,usingthecommand $lexfilename.l ThislexcompilergeneratesaCfilecalledlex.yy.c,theliteralblock,actionpartofrules section,andusersubroutinesectionoflexprogramwhereCvalidstatements willbe 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.Whennomatch,lexwritesacopyofthetokentotheoutput.Lexexecutesaction forthelongestpossiblematchforthecurrentinput. 2. ThisCfilewillbecompiledusingCcompilerandloaded,usuallywithalibraryoflex subroutines.commandforcompilingthisis $cclex.yy.cll wherellistheloaderflagaccessthelexlibrary. Theresultingprogramisplacedontheusualfilea.outforlaterexecution. 3. $a.outargumentlistifany

ISE Dept.

-6-

BNMIT,Bangalore

SSLabPrograms

6thsem

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 filename.y Yacc Compiler y.tab.c

y.tab.c

C Compiler

a.out

Sequence of tokens

a.out

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 specification of Language L ISE Dept. LexCompiler YaccCompiler -7Scanner

Parser BNMIT,Bangalore

SSLabPrograms

6thsem

IR / Target code

Structure of Yacc program


Declaration section %% Rules section %% User subroutine section 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,.......) th A symbol '$n' in the action part of the grammar rule refers to the attribute of the n 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*/ } ISE Dept. -8BNMIT,Bangalore

SSLabPrograms Compiling and executing Yacc programs: Yacc programs must be stored as filename.y Extension.

6thsem

1.FirstlexprogrammustbecompiledasusualwhichgeneratestheCfilelex.yy.c $lexfilename.l 2.ThenYaccprogrammustbecompiledwhichgeneratestheCfilecalledy.tab.c. $yaccdfilename.y ThisyacccompilergeneratesaCfilecalled y.tab.c,theliteralblock,actionpartofrules section,andusersubroutinesectionofYaccprogramwhereCvalidstatementswillbe included gets copied as it is to this C file y.tab.c. This C file contains the parser, yyparse().WhenYaccparserruns,itinturnrepeatedlycallsyylex,thelexicalanalyzerwhich suppliestokenstoyaccasandwhenrequired.Whenanerrorisdetected,parsereturnsthe value1,orthelexicalanalyzerreturnstheendmarkertokenandtheparseraccepts.Inthis case,yyparsereturnsthevalue0. 3.NowbothCfileswillbecompiledusingCcompiler. $cclex.yy.cy.tab.cllly ThisCfileswillbecompiledusingCcompilerandloaded,usuallywithalibraryofyaccandlex subroutines.lyistheloaderflagaccesstheYacclibrary. 4.Theresultingprogramisplacedontheusualfilea.outforlaterexecution.Toterminate,press Cntrl+d. $./a.out i. SpecialdirectivesandLibraryroutines: 1. 2. 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(). 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. 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. Echo : Writes the token to the current output file yyout. Equivalent to fprintf(yyout,%s,yytext); input() : Provides character to the lexer. Also yyinput() -9BNMIT,Bangalore

3.

4. 5. ISE Dept.

SSLabPrograms 6. 7. 8. 9. 10. 11. 12 12. 13 | yyleng => Stores the length of yytext. Same as strlen(yytext).

6thsem

yyparse() => The entry point to the yacc generated parser. Returns zero on success and non-zero on failure. yyerror() : Simple error reporting routine, yyerror(char *msg). % : Used to declare the definitions like %token, %start, %type, %left, %right, %union. $ => 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. => Used to define literal tokens Ex: +, -, ; => Each rule in the rule section end with a semicolon. => To specify the alternative RHS for the same LHS in a rule. Ex: e : e+e|e-e|e*e.

: => 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. 15. %left, %right, %nonassoc => Explicit means of specifying left, right, and no associativity. 16. %start <rule name> => Specifies the first rule that the parser should start. 17. %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. 18. %s or %x => Indicates start condition.

ISE Dept.

-10-

BNMIT,Bangalore

SSLabPrograms

6thsem

Part A Lex Programs


1a.LexProgramtocountthenumberofcharacters,words,lines,andblanksinagiven inputfile %{ intc_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(intargc,char*argv[]) { FILE*file; if(argc>1) { file=fopen(argv[1],"r"); if(!file) ISE Dept. -11BNMIT,Bangalore

SSLabPrograms { printf("couldnotopenfile"); exit(1); } yyin=file; yylex(); printf("TheNumberofCharacters=%d\n",c_count); printf("TheNumberofWords=%d\n",w_count); printf("TheNumberofLines=%d\n",l_count); printf("TheNumberofBlanks=%d\n",b_count); } else printf("usage:argv[0]argv[1]");} Sampleinput/output $ ./a.out infile.txt The Number of Characters=64 The Number of Words=12 The Number of Lines=3 The Number of Blanks=10 Contentsoffileinfile.txt: ThisisSystemprogrammingLab wearedoinglexandyaccprograms

6thsem

1b.ProgramtocountthenumberofcommentlinesinagivenCprogram.Also eliminatethemandcopythatprogramintoaseparatefile. %{ intcomments=0; %} %% [\t]*"/*".*"*/"[\t\n]* {comments++;} . {fprintf(yyout,yytext);} %% main(intargc,char*argv[]) { FILE*fin,*fout; if(argc>2){ fin=fopen(argv[1],"r"); ISE Dept. -12BNMIT,Bangalore

SSLabPrograms fout=fopen(argv[2],"w"); if(!fin) { printf("Couldnotopenthefile"); exit(1); } yyin=fin; yyout=fout; yylex(); printf("thenumebrofcommentsare=%d",comments); } else printf("Usage:argv[0]argv[1]argv[2]"); } Sampleinput/ouput $./a.outcprog.cresult.c thenumberofcommentsare=3 Contentsofcprog.c /*commentsection*/ main()/*main()function*/ { inta;/*declarationsection*/ } result.c main() { inta; }

6thsem

2a.programtorecognizeavalidarithmeticexpressionandidentifytheidentifiersand operatorspresent.Printthemseparately. %{ inttop=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; charstk[100],c[100],ope[100]; %} iden[azAZ]+[azAZ09]* dig[09]* ISE Dept. -13BNMIT,Bangalore

SSLabPrograms 6thsem %% {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("TheGivenArithmeticExpressionIsValid\n"); printf("TheIndividualOperatorsCountIs:\n"); printf("Plus=%d\tMinus=%d\tMultiply=%d\tDivision=%d\n",pls,min,mul,di); printf("TheIdentifiersAre:\n"); if(h>0) {for(m=0;m<h;m++) printf("%d\t",d[m]); } printf("%s\n",c); printf("TheOperatorsAre:\n"); printf("%s\n",ope); } else printf("InvalidArithmeticExpression\n"); } ISE Dept. -14BNMIT,Bangalore

SSLabPrograms Sampleinput/output $./a.out (a+d)d*g TheGivenArithmeticExpressionIsValid TheIndividualOperatorsCountIs: Plus=1Minus=1Multiply=1Division=0 TheIdentifiersAre: a d d g TheOperatorsAre: + *

6thsem

2b.Programtorecognizewhetheragivensentenceissimpleorcompound. %{ %} %% (""[aA][nN][dD]"")|(""[oO][rR]"")|(""[bB][uU][tT]"")flag=1; %% main() { yylex(); if(flag) printf("\nCompoundSentence"); else printf("\nSimplesentence"); } Sampleinput/output $./a.out RamandSita CompoundSentence $./a.out IamanIndian SimpleSentence ISE Dept. -15BNMIT,Bangalore intflag=0;

SSLabPrograms

6thsem

3.LexProgramtorecognize&countthenumberofidentifiersinagiveninputfile %{ intidc=0;

%} space[\t\n] ID[azAZ][azAZ09]* DEC({space}*"int"{space}+|{space}*"float"{space}+|{space}*"char"{space}+| {space}*"short"{space}+) %sDEF %% {DEC}{BEGINDEF;} <DEF>{ID}\, idc++; <DEF>{ID}\; {idc++;BEGIN0;} . ; %% main(intargc,char*argv[]) { FILE*f1; f1=fopen(argv[1],"r"); if(!f1) { printf("Fileopenerror"); exit(1); } yyin=f1; yylex(); printf("Thenumbersofidentifiersare%d",idc); } SampleInput/Output $./a.outinfile.c Thenumbersofidentifiersare3 Contentsofinfile.c ISE Dept. -16BNMIT,Bangalore

SSLabPrograms main() { inta,b; floatc; }

6thsem

YACCPrograms 4a.Programtorecognizeavalidityarithmeticexpressionthatusesoperators+,,*,and/ Lexprogram(say4a.l) %{ #include"y.tab.h"

%} %% [09az]+ {returnNUM;} [*+/] {returnOPR;} [] {returnSUB;} [\n] {return0;} [\t] ; . {returnyytext[0];} %% Yaccprogram(say4a.y) %{ intvalid=1; %} %tokenNUMOPRSUB %% statememt:expr expr:NUM |SUBNUM |exprOPRNUM ISE Dept. -17BNMIT,Bangalore

SSLabPrograms 6thsem |exprSUBNUM |'('expr')' |exprOPR'('expr')' |expr'('expr')' ; %% intyyerror(char*s){ valid=0; } main() { yyparse(); if(valid) printf("\nValidexpression"); else printf("\nInvalidExpression"); } Sampleinput/output $./a.out a+b Validexpression $./a.out num1num2 Validexpression $./a.out 1+2 Validexpression $./a.out (a+b)*fh Validexpression 4b.Programtorecognizeavalidvariable,whichstartswithaletter,followedbyany numberoflettersordigits. Lexprogram(say4b.l) %{ %} %% [_azAZ]+ [09] [\n] ISE Dept. #include"y.tab.h"

returnletter; returndigit; return0; -18BNMIT,Bangalore

SSLabPrograms . return0; %% YaccProgram(say4b.y) %{ intvalid=1; %} %tokenletterdigit %% statement:expr{valid=1;} expr:letter |exprletter |exprdigit ; %% intyyerror(){ valid=0; printf("\nInvalidvariable\n"); } main() { yyparse(); if(valid) printf("\nValidVariable"); } Sampleinput/output $./a.out Num1 ValidVariable $./a.out 345 Invalidvariable

6thsem

5a.Programtoevaluateanarithmeticexpressioninvolvingoperators+,,*,and/. LexProgram(say5a.l) %{ #include"y.tab.h" externintyylval; %} %% [09]+ {yylval=atoi(yytext);returnNUM;} ISE Dept. -19BNMIT,Bangalore

SSLabPrograms [\t] ; [\n] return0; . returnyytext[0]; %% YaccProgram(say5a.y) %{ intvalid=1; %} %tokenNUM %left'+','' %left'*','/' %leftUMINUS %% 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%precUMINUS {$$=$2;yylval=$$;} ; %% intyyerror() { valid=0; } main() { yyparse(); if(valid) { printf("\nValidExpression\n"); printf("Result=%d",yylval); } else printf("\nInvalidExpression");}

6thsem

ISE Dept.

-20-

BNMIT,Bangalore

SSLabPrograms Sampleinput/output $./a.out 1+2 ValidExpression Result=3 $./a.out 47 ValidExpression Result=11

6thsem

5b.YaccProgramtorecognizestrings'aaabbb','aabb'and'ab'usingthegrammar{anbn wheren>0} LexProgram(say5b.l) %{ #include"y.tab.h" %} %% [a] returnA; [b] returnB; [\n] return0; . return0; %% YaccProgram(say5b.y) %{ intvalid=1; %} %tokenAB %% start:expr|line; expr:AexprB|AB line: ; %% yyerror(char*s){ printf("\nInvalidgrammar"); valid=0; } intmain() { yyparse(); ISE Dept. -21BNMIT,Bangalore

SSLabPrograms if(valid) printf("\nValidgrammar"); } Sampleinput/output $./a.out aabb Validgrammar $./a.out abb Invalidgrammar

6thsem

6.Programtorecognizethegrammaranbwheren>=0.LexProgram(say6.l) %{ #include"y.tab.h" %} %% [a] returnA; [b] returnB; \n return0; . return0; %% YaccProgram(say6.y) %{ intvalid=1; %} %tokenAB %% start:expr; expr:expr2expr1B|expr2B; expr1:expr1A|A; expr2:AAAAAAAAAA; %% intyyerror(char*s){ valid=0; } intmain(){ yyparse(); if(valid) printf("\nValidGrammar"); ISE Dept. -22BNMIT,Bangalore

SSLabPrograms else

6thsem printf("\nInvalidGrammar");

} Sampleinput/output [root@localhostSPL]#./a.out aab InvalidGrammar $./a.out aaaaaaaaaab ValidGrammar

PART - B 1a.Writeanonrecursiveshellscriptthatacceptsanynumberofarguments&printsthem inthereverseorder. if[$#eq0] then echoNocommandlinearguments\n exit0 fi echo"Inputstringis:$*" forxin"$@" do y=$x""$y done echo"Reversedstringis:$y" Sampleinput/output $sh1a.shabcd Inputstringis:abcd Reversedstringis:dcba 1b.WriteaCprogramthatcreatesachildprocesstoreadcommandsfromstandardinput &executethem #include<stdio.h> ISE Dept. -23BNMIT,Bangalore

SSLabPrograms intmain() { charstr[10]; intpid,i; pid=fork(); if(pid==0) { printf("Childprocess..."); do { printf("\nEnteracommand:"); scanf("%s",str); system(str); printf(Enter1:Continue0:exit); scanf(%d,&i); }while(i!=0); printf("childprocesshasterminated\n"); } else { wait(); printf("\nParentProcess"); } return0;} Sampleinput/output #./a.out Childprocess... Enteracommand:date WedFeb721:52:00IST2007 Enter1:Continue0:exit 0 childprocesshasterminated ParentProcess

6thsem

2a.Writeashellscriptthatacceptstwofilenamesasarguments,checksifthepermissions forthesefilesareidentical&ifthepermissionsareidentical,ouputsthecommon permissions,otherwiseoutputseachfilenamesfollowedbyitspermissions if[$#eq0] then echoNocommandlinearguments\n ISE Dept. -24BNMIT,Bangalore

SSLabPrograms exit0 fi f1=`lsl$1|cutc210` f2=`lsl$2|cutc210` if[$f1==$f2] then echo"files$1&$2havecommonfilepermissions:$f1" else echoFile$1and$2havedifferentpermission echo"file$1hasfilepermissions:$f1" echo"file$2hasfilepermissions:$f2" fi Sampleinput/output $sh2a.sh4a.l4a.sh file4a.lhasfilepermissions:rwrr file4a.shhasfilepermissions:rwxrxrx #sh2a.sh1a.sh1b.c files1a.sh&1b.chavecommonfilepermissions:rwxrxrx

6thsem

2b.WriteaCprogramtocreateafilewith16bytesofarbitrarydatafrothebeginningand another16bytesofarbitrarydatafromanoffsetof48.Didplaythefilecontentsto demonstratehowtheholeinfileishandled. #include<sys/types.h> #include<stdlib.h> #include<sys/stat.h> #include<fcntl.h> #include<stdio.h> #include<unistd.h> intmain() { charbuf1[]="123456789ABCDEFG"; charbuf2[]="HIJKLMNOPQRSTUVW"; intfd; fd=creat("t.txt",O_WRONLY); write(fd,buf1,16); lseek(fd,48,SEEK_SET); write(fd,buf2,16); printf(thecontentsofthefileare\n); system(vit.txt); ISE Dept. -25BNMIT,Bangalore

SSLabPrograms 6thsem exit(0); } Sampleinput/output $./a.out $ t.txtfilelooksas 123456789ABCDEFG^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@ ^@^@^@^@^@^@^@^@^@^@^@^@^@HIJKLMNOPQRSTUVW 3a.Shellscriptthattakesavaliddirectorynamesasanargumentandrecursivelydescents allthesubdirectoriesfindsthemaximumlengthofanyfileinthathierarchyandwritesthis maximumvaluetothestandardoutput.

if[$#ne1] then echo"Usage:$0directory" exit1 fi lsRl$1|grep"^"|sortnk5,9|teef1 echo"maximumlengthoffileis" tail1f1|cutc3665 Sampleinput/output $sh3a.sh. rwrr1rootroot76Feb721:43y.tab.h rwrr1rootroot90Feb720:37cprog.c rwrr1rootroot120Feb622:596.l rwrr1rootroot130Feb622:335b.l rwrr1rootroot152Feb623:154b.l rwrr1rootroot176Feb622:185a.l maximumlengthoffileis 176722:105a.l

ISE Dept.

-26-

BNMIT,Bangalore

SSLabPrograms

6thsem

3b.WriteaCProgramthatacceptsvalidfilenamesascommandlinearguments&for eachofthearguments,printsthetypeofthefile(Regularfile,Directoryfile,Character devicefileetc) #include<sys/stat.h> #include<unistd.h> #include<stdio.h> intmain(intargc,char*argv[]) { inti; structstatfile; for(i=1;i<argc;i++) { if(lstat(argv[i],&file)!=0) {printf("File%sdoesnotexits",argv[i]);continue;} printf("\nFile%sisa",argv[i]); if(S_ISREG(file.st_mode)) printf("RegularFile"); elseif(S_ISDIR(file.st_mode)) printf("DirectoryFile"); elseif(S_ISCHR(file.st_mode))printf("CharacterDeviceFile"); elseif(S_ISBLK(file.st_mode))printf("BlockDeviceFile"); elseif(S_ISFIFO(file.st_mode))printf("FIFOFile"); #ifdefS_IFLINK elseif(S_ISLINK(file.st_mode)) printf("SymbolicLinkFile"); #endif }} Sampleinput/output $./a.out3a.sh File3a.shisaRegularFile $./a.out3a.sh/dev/hda4 File/dev/hda4isaBlockDeviceFile 4a.shellscriptthatacceptsfilenamespecifiedasarguments&createsashellscriptthat containsthisfileaswellasthecodetorecreatethesefiles.Thusifthescriptgeneratedby yourscriptisexecuteditwouldrecreatetheoriginalfiles forxin$* do echo"cat>$x<<ENDM abc ISE Dept. -27BNMIT,Bangalore

SSLabPrograms def ghi ENDM" done>recreate Sampleinput/output $sh7a.shfile1file2 $virecreate cat>file1<<here abc def ghi here cat>file2<<here abc def ghi here $shrecreate $ls file1file2recreate $catfile1 abc def ghi $catfile2 abc def ghi

6thsem

4b.writeaCprogramtocreatechildprocess.thechildprocessprintsitsownprocessid andidofitsparentandthenexits.theparentprocesswaitsforitschildtofinish&prints itsownprocessid&theidofitschildprocessandthenexits. #include<stdio.h> intmain() { charstr[10]; intpid; pid=fork(); ISE Dept. -28BNMIT,Bangalore

SSLabPrograms if(pid==0) { printf("Childprocess..."); printf("\n\nChildPID:%d",getpid()); printf("\nParentPID:%d",getppid()); printf("\n\nFinishedwithchild\n"); } else { wait(); printf("\nParentprocess"); printf("\nPARENTPID:%d",getpid()); printf("\nChildPID:%d",pid); } return0; } Sampleinput/output ./a.out Childprocess... ChildPID:4145 ParentPID:4144 Finishedwithchild Parentprocess PARENTPID:4144 ChildPID:4145

6thsem

5a.Shellscriptthatacceptspathnamesandcreatesallthecomponentsinthatpathnames asdirectories.Forexample,ifthescriptnameismpe,thenthecommandmpea/b/c/d shouldcreatedirectoriesa,a/b,a/b/canda/b/c/d if[$#eq0] then echo"Usage:$0[dir]/[sub]...." exit1 fi IFS='/' fordirnamein$* do mkdir$dirname ISE Dept. -29BNMIT,Bangalore

SSLabPrograms cd$dirname done Sampleinput/output $sh4a.sha/b/c/d

6thsem

5b.Cprogramthatacceptsonecommandlineargument,executestheargumentasshell command.determinesthetimetakenbyitandprintthetimevalues #include<time.h> #include<unistd.h> #include<sys/types.h> #include<sys/times.h> intmain(intargc,char*argv[]) { clock_tstart,finish; structtmss,e; floattime; floatclktck=sysconf(_SC_CLK_TCK); start=times(&s); system(argv[1]); finish=times(&e); time=(finishstart)/clktck; printf("realtimetakentoexecutecommand:%sis%f",argv[1],time); printf("\nusertime%f",(s.tms_utimee.tms_utime)/clktck); printf("\nsystemtime%f",(s.tms_stimee.tms_stime)/clktck); return0;} Sampleinput/output $./a.outdate WedFeb722:30:56IST2007 realtimetakentoexecutecommand:dateis0.020000 usertime0.000000 systemtime0.000000 6a.Shellscriptthatacceptsvalidloginnamesasarguments&printstheircorresponding homedirectories.ifnoargumentsarespecified,printasuitableerrormessage. if[$#eq0] then echoNocommandlinearguments\n exit0 fi ISE Dept. -30BNMIT,Bangalore

SSLabPrograms fornamin"$@" do grep"^$nam"/etc/passwd>list if[$?eq0] then echohomedirectoryof$namis cutd":"f1,6list else echo\n$namisimproperloginname fi done Sampleinput/ouput $sh5a.shrootmysqlabc Homedirectoryofrootis /root Homedirectoryofmysqlis /var/lib/mysql abcisimproperloginname

6thsem

6b.Cprogramthatacceptsvaliddirectorynamesasacommandlineargumentandlistall filesinthegivendirectoryaswellassubdirectories(implementationoflslR) #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]); else exit(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); return 0; }

ISE Dept.

-31-

BNMIT,Bangalore

SSLabPrograms 6thsem Sampleinput/output $./a.out/root/SPL Recursivelydescendinginto/root/SPLdirectory DIR/root/SPL: SPLabManual.doc10a.awk1b.cfile27a.shf12b.c3.ltest2.ct18a.sh outfile.txt6.l3a.sfile14a.sh6b.cresult.c5b.yout.txt1b.ly.tab.hg1 5b.c3a.sh~2a.shg29b.pl4a.ytestcprog.c5b.l1.sh3b.c2a.l~recreate y.tab.c2a.ltest.c4a.l2b.l8b.plfile3a.out.txtt2gsg4b.y5a.sh10b.c a7b.awk9a.sh4b.llex.yy.c5a.l5a.y1a.l2a.l,v6.y1a.sh SPLabManual.sxw4b.cinfile.txt6a.sh 7a.Writeashellscripttoimplementterminallocking.Itshouldprompttheuserfora password.Ifamatchoccurs,itmustlocktheterminal&promptforthepassword.Ifthe properpasswordisentered,theterminalmustbeunlocked. trap''123812151820 sttyecho echoenterthepassword readp1 echoreenterthepassword readp2 if[$p1=$p2"] then echoterminallocked echotoinvokereenterthepassword readp3 while["$p3"!="$p1"] do echopasswordenteredisnotmatching echoreenterthepassword readp3 done echoterminalunlocked fi sttysane Sampleinput/output $sh6a.sh enterthepasswordgsg reenterthepasswordgsg ISE Dept. -32BNMIT,Bangalore

SSLabPrograms terminallocked toinvokereenterthepasswordgsg terminalunlocked

6thsem

7b.Cprogramtoprompttheuserforthenameofanenvironmentvariableandprintits valueifitsdefinedandasuitablemessageotherwiseandtorepeattheprocessifuser wantsit. #include<stdio.h> #include<stdlib.h> intmain(void) { charenvvar[10]; char*value; intchoice; do { printf("Entertheenvironmentvar:"); scanf("%s",envvar); value=getenv(envvar); if(value!=NULL) printf("%shasthevalue:%s",envvar,value); else printf("%sisnotdefined"); printf("\nDouwanttocontinue:"); scanf("%d",&choice); }while(choice); return0; } Sampleinput/output ./a.out Entertheenvironmentvar:PWD PWDhasthevalue:/root/SPL Douwanttocontinue:0

ISE Dept.

-33-

BNMIT,Bangalore

SSLabPrograms

6thsem

VIVAQuestions PartA 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. PartB 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. ISE Dept. ExplainthefeatureofUnixOS? ExplainthedifferentfilesinUNIXsystem? Whatisfork?Explainthefork()function? Explainthedifferencebetweenforkandvfork? Explainhowsystemfunctionworks? Explainthestructurestat? Explainstat,fstat,lstatfunctions? Whatisprocess?Explaintheparentchildrelationship. Explainthegetpid,getppid,getuid,geteuid,getgid,getegitfunctions? Whatarethemainfunctionsofshell? Whatarethestepsinvolvedincreatingchildprocess? Whatarepositionalparameters? ExplaindifferentexecfunctioninUNIX? Whatareenvironmentalvariables? Whatis$*,$#,$$,$_,$! -34BNMIT,Bangalore Whatislex? Whatisyacc? Whatarethedifferentphasesofcomplier? Definetoken.Howtheyarerecognizedbythescanners? Whataredifferentdatastructuresusedbyassembler? Whatarethefunctionsofassembler? Whatisregularexpression? Whatisgrammer? Explainthestructuresoflexandyaccprograms. Whatisloader?Whataretypesofloaders?

SSLabPrograms 16. Wheredoyouuseexprinshellscripts? 17. Whatisheredocument? 18. Whatisshellscript?Howitisdifferentformcprogram? 19. Whatdoyoumeanbyexitstatusofacommand? 20. Wheredoyouusecutcommand? 21. Differentiateheadandtail? 22. Whatissetcommand? 23. Whatisthefunctionoflseek()? 24. Explaingetenvfunction? 25. Explaintheusageoftrapcommand? 26. Howcanyouchangethefilepermissions?

6thsem

ISE Dept.

-35-

BNMIT,Bangalore