Top Banner

of 27

55229925 System Software Lab Manual

Apr 07, 2018

Download

Documents

Anupam Chougule
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
  • 8/4/2019 55229925 System Software Lab Manual

    1/27

    Sir MVIT Dept of Computer Science & Engg

    SIR M. VISVESVARAYA INSTITUTE OF TECHNOLOGY

    (Affiliated to VTU & recognized by AICTE, New Delhi)

    ACCREDATED BY NBA

    Department Of Computer Science & Engineering

    SYSTEM SOFTWARE AND COMPILER DESIGNLABORATORY

    06CSL68

    6TH SEMESTER

    Prepared & Compiled By, Under Guidance of,

    Mrs. Salma Banu N K Prof. Dilip K Sen

    Lecturer, Dept. Of CS&E HOD, Dept. Of CSE

    System Software Lab Manual 1 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    2/27

    Sir MVIT Dept of Computer Science & Engg

    SIR M. VISVESVARAYA INSTITUTE OF TECHNOLOGYBANGALORE

    DEPT. OF COMPUTER SCIENCE AND ENGG.

    SYSTEM SOFTWARE AND COMPILER DESIGN LABORATORY

    Subject Code: 06CSL68 Sem : 6 th CSE Max Marks : 50

    Part ALEX AND YACC PROGRAMS:

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

    Execution of 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 (an bn, n>= 0).

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

    PART BUNIX PROGRAMMING:

    1) a. Non-recursive shell script that accepts any number of arguments and prints them inthe Reverse order, ( For example, if the script is named rargs, then executing rargsA 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 assumethat 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 commonpermissions, 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

    System Software Lab Manual 2 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    3/27

    Sir MVIT Dept of Computer Science & Engg

    another 16 bytes of arbitrary data from an offset of 48. Display the file contents todemonstrate how the hole in file is handled.

    3) a. Shell function that takes a valid directory names as an argument and Recursivelydescends all the subdirectories, finds the maximum length 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 specialfile, Block special file, Symbolic link etc.)

    4) a. Shell script that accepts file names specified as arguments and creates a shell scriptthat contains this file as well as the code to recreate these files. Thus if the scriptgenerated by your script is executed, it would recreate the original files(This is same asthe bundle script described by Brain W. Kernighan and Rob Pike in The UnixProgramming 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 itschild process and then exits.

    COMPILER DESIGN:

    5) Write a C program to implement the syntax-directed definition of if E then S1 andif E then S1 else S2. (Refer Fig. 8.23 in the text book prescribed for 06CS62

    Compiler Design, Alfred V Aho, Ravi Sethi, Jeffrey D Ullman: Compilers- Principles,Techniques and Tools, Addison-Wesley, 2007.)

    6) Write a yacc program that accepts a regular expression as input and produce its parsetree as output.

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

    System Software Lab Manual 3 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    4/27

    Sir MVIT Dept of Computer Science & Engg

    PART ALEX :

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

    input file.

    %{#includeint cc=0,bc=0,wc=0,lc=0;%}%%[^ \t\n]+ { wc++;

    cc=cc+yyleng;}

    \n lc++;

    " " bc++;\t bc=bc+5;%%main(int argc,char *argv[]){

    if (argc!=2) {printf("\nusage:./a.out filename\n");return(0);

    }yyin=fopen(argv[1],"r");yylex();

    printf("\n no of lines are %d\n",lc); printf("\n no of words are %d\n",wc); printf("\n no of blanks are %d\n",bc); printf("\n no of character are %d\n",cc);

    }

    Sample Input/Output:

    $ lex prga1a.l$ cc lex.yy.c$ ./a.out ben10

    no of lines areno of words areno of blanks areno of character

    System Software Lab Manual 4 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    5/27

    Sir MVIT Dept of Computer Science & Engg

    $ cat ben10Ben discovers a strange device, the Omnitrix, which locks itself on his wrist.Each alien has its own set of special abilities that Ben can use, while at the sametime still maintaining his 10-year-old personality.

    1) b. Program to count the numbers of comment lines in a given C program. Alsoeliminate them and copy the resulting program into separate file.

    %{#includeint c=0;%}%%("/*"[ a-zA-Z0-9\n\t]*"*/") c++;

    ("//"[\n]?[ a-zA-Z0-9]*) c++;[a-zA-Z0-9(){}.\;#]* {fprintf(yyout,"%s",yytext);}%%

    main(int argc,char *argv[]){

    if(argc!=3) {printf("\nusage:");return(0);

    }yyin=fopen(argv[1],"r");

    yyout=fopen(argv[2],"w");yylex();printf("\n no of comment lines is %d",c);

    }

    Sample Input/Output :

    $vi prga1b.l$ lex prga1b.l$ cc lex.yy.c -lfl$ ./a.out test.c out.c

    no of comment lines is 4

    $ cat out.c

    #includeint main(){

    System Software Lab Manual 5 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    6/27

    Sir MVIT Dept of Computer Science & Engg

    int a,b; printf("this is test program ");return 0;}

    $ cat test.c

    /* this is for counting the no of comment lines in a given prog. */#includeint main(){int a,b; //data type declaration

    printf("this is test program "); /* this is for printing */return 0;} //end of main program

    2) a. Program to recognize a valid arithmetic expression and to recognize theidentifiers and operators present. Print them separately.

    %{#includeint nplus=0,nminus=0,nmul=0,id=0,ndiv=0,flag1=0,flag2=0;%}%%[(] {flag1++;}[)] {flag1--;}[ a-zA-Z0-9]+ {flag2++;id++;}

    [+] {flag2--;nplus++;}[-] {flag2--;nminus++;}[*] {flag2--;nmul++;}[/] {flag2--;ndiv++;}%%main(){

    printf("\nenter a valid arithematic expression\n");yylex();if(flag1!=0||flag2!=1)

    printf("invalid expression");

    else { printf("\nValid expression\n"); printf("addition(+)=%d\n",nplus); printf("subtraction(-)=%d\n",nminus); printf("multiplication(*)=%d\n",nmul); printf("division(/)=%d\n",ndiv); printf("\nid=%d",id);

    }

    System Software Lab Manual 6 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    7/27

    Sir MVIT Dept of Computer Science & Engg

    }

    Sample Input/Output :

    $ lex prog2a.l

    $ cc lex.yy.c -lfl$ ./a.out

    enter a valid arithmetic expression(a+d)/c

    ctrl+dValid expressionaddition(+)=1subtraction(-)=0multiplication(*)=0division(/)=1

    id = 32) b. Program to recognize whether a given sentence is simple or compound .

    %{#includeint flag=0;%}%%[\t\n]+ ;([aA][nN][dD]) flag=1;("or") {flag=1;}("nevertheless") {flag=1;}("inspite") {flag=1;}("because") {flag=1;}. ;%%main(){

    printf("\n\n enter the sentence\n");yylex();if(flag==0)

    printf("\n\n sentence is simple\n");else

    printf("\n\n sentence is compund\n");}

    System Software Lab Manual 7 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    8/27

    Sir MVIT Dept of Computer Science & Engg

    Sample Input/Output :

    Run 1:

    $ lex prog2b.l$ cc lex.yy.c -lfl$ ./a.out

    enter the sentence

    Noddy and his friends have been exploring the magical world.

    sentence is compound

    Run 2: $ ./a.outenter the sentence

    A shooting star, in a galaxy far far away.

    Sentence is simple

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

    %{

    #includeint count=0;%}%%"int" |"float" |"double" |"char" { char ch;

    ch=input();while(1) {

    if(ch==',') count++;

    if(ch==';') { count++;break;

    }if(ch=='\n') break;

    ch=input();}

    }

    System Software Lab Manual 8 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    9/27

    Sir MVIT Dept of Computer Science & Engg

    . | '\n' ;%%int main(int argc,char *argv[]){

    if(argc!=2)

    printf("\n\nINVALID INPUT\n\n");else {yyin=fopen(argv[1],"r");

    if(yyin) {yylex();

    printf("\nNo of identifiers = %d\n",count);} else

    printf("\nError in opening the file\n");}

    printf("\n");}

    Sample Input/Output :

    $ lex prg3.l$ cc lex.yy.c -lfl$ ./a.out out.c

    No of identifiers = 1

    $ cat out.c//to print a message

    // hello*/

    #includemain(){

    int var=0; //dummy variablr writef("hello");//aprint the messagegetch();

    }

    System Software Lab Manual 9 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    10/27

    Sir MVIT Dept of Computer Science & Engg

    PART AYACC :

    4) a. Program to recognize a valid arithmetic expression that uses operators +, -, *

    and /.

    Lex part :

    %{#include "y.tab.h"%}%%[a-zA-Z] {return ALPHA;}[0-9]+ {return NUMBER;}[\t\n]+ ;

    . {return yytext[0];}%%

    Yacc part :

    %{#include%}%token NUMBER ALPHA%left '+''-'%left '*''/'

    %left '('')'%%expr:'+'expr

    |'-'expr |expr'+'expr |expr'-'expr |expr'*'expr |expr'/'expr |'('expr')'|NUMBER |ALPHA

    ;%%int main(){

    printf("enter an arithematic expression\n");yyparse();printf("arithematic expression is valid\n");return 0;

    System Software Lab Manual 10 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    11/27

    Sir MVIT Dept of Computer Science & Engg

    }int yyerror(char *msg){

    printf("\n%s",msg);printf("\narithematic expression is invalid");

    exit(0);}

    Sample Input/Output :

    $ lex prog1.l$ yacc -d prog1.y$ cc -c lex.yy.c y.tab.c$ cc -o a.out lex.yy.o y.tab.o -lfl$ ./a.outenter an arithmetic expression

    (a+d)*(c-e)Arithmetic expression is valid

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

    Lex Part :

    %{#include "y.tab.h"

    %}%%[a-zA-Z] return L;[a-zA-Z0-9] return D;. return P;%%

    Yacc Part :

    %{#include%}%token L D P%%var:L XX:X D| {printf("\nvalid variable"); return 0;}P { ; }%%main(){

    printf("\nEnter variable");

    System Software Lab Manual 11 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    12/27

    Sir MVIT Dept of Computer Science & Engg

    yyparse();}yyerror(){

    printf("\nInvalid variable");

    }

    Alternate Program

    %{#include#include%}%token LETTER DIGIT%%var : LETTER st '\n' {printf("\nValid variable\n");return 0;}

    ;st : LETTER | DIGIT| DIGIT st| LETTER st;

    %%

    int yylex(){

    char c;while((c=getchar())==' '||c=='\t');if(isalpha(c)) return LETTER;if(isdigit(c)) return DIGIT;return c;

    }

    int main(){

    printf("\nEnter the variable : ");yyparse();return 0;}

    int yyerror(){

    printf("\nInvalid variable\n");return 0;}

    System Software Lab Manual 12 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    13/27

    Sir MVIT Dept of Computer Science & Engg

    Sample Input/Output :

    1 run :

    $ lex prog4b.l$ yacc -d prog4b.y$ cc -c lex.yy.c y.tab.c$ cc -o a.out lex.yy.o y.tab.o -lfl$ ./a.out

    Enter variable:#71Invalid variable

    2 run :

    Enter variable:number71valid variable

    3 run :Enter variable:7edf Invalid variable

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

    Lex part :%{#include#include"y.tab.h"extern int yylval;%}

    %%[0-9]+ { yylval=atoi(yytext);

    return NUM;}

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

    Yacc Part

    %{

    System Software Lab Manual 13 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    14/27

    Sir MVIT Dept of Computer Science & Engg

    #include%}%token NUM%left '+' '-'%left '*' '/'

    %left '(' ')'%%expr: e

    { printf("result:%d\n",$$);return 0;

    }e:e'+'e {$$=$1+$3;}|e'-'e {$$=$1-$3;}|e'*'e {$$=$1*$3;}|e'/'e {$$=$1/$3;}|'('e')' {$$=$2;}

    | NUM {$$=$1;};%%

    main(){

    printf("\n enter the arithmetic expression:\n");yyparse();

    printf("\n valid expression\n");}

    yyerror(){

    printf("\n invalid expression\n");exit(0);}

    Sample Input/Output :

    $ lex prog5.l$ yacc -d prog5.y$ cc -c lex.yy.c y.tab.c$ cc -o a.out lex.yy.o y.tab.o -lfl$ ./a.out

    enter the arithematic expression:5+6result:11

    valid expression

    System Software Lab Manual 14 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    15/27

    Sir MVIT Dept of Computer Science & Engg

    5 b) Program to recognize strings 'aaab', 'abbb', 'ab', 'a' using the grammer.(a n b n ,n>=0)

    Lex part :

    %{#include "y.tab.h"%}%%a return A;

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

    Yacc Part :

    %{#includeint valid=1;%}%token A B%%str:S'\n' {return 0;}S:A S B|;

    %%main(){

    printf("Enter the string:\n");yyparse();if(valid==1)

    printf("\nvalid string");}

    yyerror(){

    valid=0; printf("\ninvalid string");return 1;}

    Sample Input/Output :

    $ lex prog5b.l$ yacc -d prog5b.y

    System Software Lab Manual 15 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    16/27

    Sir MVIT Dept of Computer Science & Engg

    $ cc -c lex.yy.c y.tab.c$ cc -o a.out lex.yy.o y.tab.o -lfl$ ./a.outEnter the string:aaaabb

    Invalid string

    Enter the string:aaabvalid string

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

    Lex Part :

    %{#include "y.tab.h"%}%%a return A;

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

    Yacc Part :

    %{#includeint valid=1;%}%token A B%%str:S'\n' {return 0;}S:A S B|

    ;%%main(){

    printf("Enter the string:\n");yyparse();if(valid==1)

    printf("\nValid string");

    System Software Lab Manual 16 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    17/27

    Sir MVIT Dept of Computer Science & Engg

    }

    yyerror(){valid=0;

    printf("\nInvalid string");return 1;}

    Sample Input/Output :

    $ lex prog6.l$ yacc -d prog6.y$ cc -c lex.yy.c y.tab.c$ cc -o a.out lex.yy.o y.tab.o -lfl$ ./a.out

    Enter the string:aaaabbInvalid stringEnter the string:aaaaaaaaaabvalid string

    PART BUnix Programming:

    Shell Programming :

    The Shell is one of the major components of the Unix system. As a commandinterpreter, it provides an interface between the user and the operating system.The shell is also a programming language that executes shell scripts in theinterpretive mode one line at a time.

    The Shell programs or shell scripts are executable text files that contain UNIXcommands.

    The Unix Systems offers a variety of shells like Bourne shell , C shell, Kornshell and bash(born again shell) shell for you to choose.

    Shell scripts are typically written when:there is a command or string of commands that you will use more thanonce.you want access to command line argumentsyou need looping and testing.

    System Software Lab Manual 17 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    18/27

    Sir MVIT Dept of Computer Science & Engg

    Writing and running a Shell Script

    1. Use your vi editor to create the shell script2. To run the script, use sh followed by the name of the shell script.

    For example,

    $ sh filename.shWhen used in this way, the script doesnt need to have executable permission.

    OR To run the script, make it executable and invoke the script name.

    For example,$ chmod +x filename.sh$ filename.sh

    Simple Shell script

    Shell script (named first) that displays the current date, the users on the systemand a welcome message for the user logged in.

    datewhoecho Welcome $LOGNAME

    $ sh first.shSat Sep 30 14:42:39 PDT 2007root tty01 Sep 30 13:32welcome root

    1) a. Non-recursive shell script that accepts any number of arguments and printsthem in the Reverse order, (For example, if the script is named ranges, thenexecuting ranges A B C should produce C B A on the standard output).

    echo "Input 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

    System Software Lab Manual 18 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    19/27

    Sir MVIT Dept of Computer Science & Engg

    1) b. C program that creates a child process to read commands from the standardinput and execute them (a minimal implementation of a shell like program). Youcan assume that no arguments will be passed to the commands to be executed.

    #include

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

    {printf("Child process...");printf("\nEnter a command:");scanf("%s",str);system(str);

    printf("Finished with child");}else

    {wait();

    printf("\nParent Process");}return 0; }Sample input/output :

    $ ./a.outChild process...Enter a command:dateWed Feb 7 21:52:00 IST 2007Finished with childParent Process

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

    f1=`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 has file permissions : $f1"echo "file $2 has file permissions : $f2"

    System Software Lab Manual 19 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    20/27

    Sir MVIT Dept of Computer Science & Engg

    fi

    Sample input/output :

    Run 1:

    $ sh 2a.sh 4a.l 4a.shfile 4a.l has file permissions : rw-r--r--file 4a.sh has file permissions : rwxr-xr-x

    Run 2:

    $ sh 2a.sh 1a.sh 1b.cfiles 1a.sh & 1b.c have common file permissions: rwxr-xr-x

    2) b. Write a C program to create a file with 16 bytes of arbitrary data fro thebeginning 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.

    #include#include#include#include#include

    int main(){

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

    }

    Sample input/output :$ ./a.out$ vi t.txt

    t.txt file looks as123456789ABCDEFG^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@HIJKLMNOPQRSTUVW

    System Software Lab Manual 20 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    21/27

    Sir MVIT Dept of Computer Science & Engg

    3) a. Shell script that takes a valid directory names as an argument and recursivelydescents all the subdirectories, finds the maximum length of any file in thathierarchy 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 d f 5,8

    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

    3) b. 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 special file, Block special file, Symbolic link etc.)

    #include #includeint main(int argc,char* argv[]){

    int i;struct stat file;for(i=1;i

  • 8/4/2019 55229925 System Software Lab Manual

    22/27

    Sir MVIT Dept of Computer Science & Engg

    else if(S_ISFIFO(file.st_mode)) printf("FIFO File");#ifdef S_IFLINK else if(S_ISLINK(file.st_mode)) printf("Symbolic Link File");#endif else if(S_ISSOCK(file.st_mode)) printf("Socket File");

    } }

    Sample input/output :

    Run 1:$ ./a.out 3a.shFile 3a.sh is a Regular File

    Run 2:

    $ ./a.out 3a.sh /dev/hda4

    File /dev/hda4 is a Block Device File4) a. Shell script that accepts file names specified as arguments and creates a shellscript that contains this file as well as the code to recreate these files. Thus if thescript generated by your script is executed, it would recreate the original files (Thisis same as the bundle script described by Brain W. Kernighan and Rob Pike in

    The Unix Programming Environment, Prentice Hall India).

    for x in $*doecho "cat > $x

  • 8/4/2019 55229925 System Software Lab Manual

    23/27

    Sir MVIT Dept of Computer Science & Engg

    here$ sh recreate$ lsfile1 file2 recreate$ cat file1

    abcdef ghi$ cat file2abcdef ghi

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

    int main(){

    char str[10];int pid;

    pid=fork();if(!pid){

    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 : 4145 Parent processParent PID : 4144 PARENT PID : 4144Finished with child Child PID : 4145

    System Software Lab Manual 23 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    24/27

    Sir MVIT Dept of Computer Science & Engg

    COMPILER DESIGN:

    5. Write a C program to implement the syntax-directed definition of if E then S1and if E then S1 else S2. (Refer Fig. 8.23 in the text book prescribed for 06CS62Compiler Design, Alfred V Aho, Ravi Sethi, Jeffrey D Ullman: Compilers-Principles, Techniques and Tools, Addison-Wesley, 2007.)

    #include#include#includeint parsecondition(char[],int,char*,int);void gen(char[],char[],char[],int);int main(){

    int counter=0,stlen=0,elseflag=0;char stmt[60];char strB[54];char strs1[50];char strs2[45];

    printf("\nFormat of 'if' statement \nExample : \n"); printf(" if( a < b ) then ( s = a );\n");

    printf(" if( a < b ) then ( s = a ) else ( s = b );\n\n");printf("Enter the statement \n");scanf("%[^\n]s",stmt);

    stlen=strlen(stmt);counter=counter+2; //increment over 'if'counter=parsecondition(stmt,counter,strB,stlen);if(stmt[counter]==')')

    counter++;counter=counter+3;counter=parsecondition(stmt,counter,strs1,stlen);if(stmt[counter+1]==';'){

    printf("\nParsing the input statement...");gen(strB,strs1,strs2,elseflag);return 0;

    }if(stmt[counter]==')')

    counter++;counter=counter+3;counter=parsecondition(stmt,counter,strs2,stlen);counter=counter+2;if(counter==stlen){

    System Software Lab Manual 24 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    25/27

    Sir MVIT Dept of Computer Science & Engg

    elseflag=1; printf("\nParsing the input statement..");gen(strB,strs1,strs2,elseflag);return 0;

    }

    return 0;}int parsecondition(char input[],int cntr,char *dest,int totallen){

    int index=0,pos=0;while(input[cntr]!='(' && cntr=totallen)

    return 0;index=cntr;while(input[cntr]!=')') cntr++;

    if(cntr>=totallen)return 0;while(index

  • 8/4/2019 55229925 System Software Lab Manual

    26/27

    Sir MVIT Dept of Computer Science & Engg

    6. Write a yacc program that accepts a regular expression as input and produce itsparse tree as output.%{#includechar str[20];

    int i=0;%}%token id%left '+''/''*''-'%%E : S {infix_postfix(str);}S : S '+' T

    | S '-' T| T

    T : T '*' F| T '/' F

    | FF : id| '(' S ')';

    %%#includemain(){

    printf("\nEnter an expression : ");yyparse();}yyerror(){

    printf("invalid");}yylex(){char ch=' ';while(ch!='\n'){ch=getchar();str[i++]=ch;if(isalpha(ch)) return id;if(ch=='+'||ch=='*'|| ch=='-'||ch=='/') return ch;}str[--i]='\0';return(0);exit(0);}void push(char stack[],int *top,char ch){

    stack[++(*top)]=ch;}

    System Software Lab Manual 26 / 27 Prepared By, Salma Banu N K

  • 8/4/2019 55229925 System Software Lab Manual

    27/27

    Sir MVIT Dept of Computer Science & Engg

    char pop(char stack[],int *top){

    return(stack[(*top)--]);}

    int prec(char ch){ switch(ch){

    case '/':case '*': return 2;case '+':case '-': return 1;case '(': return 0;default: return -1;}}

    void infix_postfix(char infix[]){

    int top=-1,iptr=-1,pptr=-1;char postfix[20],stack[20],stksymb,cursymb; push(stack,&top,'\0');while((cursymb=infix[++iptr])!='\0'){

    switch(cursymb){ case '(': push(stack,&top,cursymb);

    break;case ')': stksymb=pop(stack,&top);

    while(stksymb!='('){

    postfix[++pptr]=stksymb;stksymb=pop(stack,&top);

    } break;

    case '*':case '/':case '+':case '-': while(prec(stack[top])>=prec(cursymb))

    postfix[++pptr]=pop(stack,&top);push(stack,&top,cursymb);

    break;default: if(isalnum(cursymb)==0)

    {printf("Error in input!"); exit(0);}postfix[++pptr]=cursymb; }}

    while(top!=-1)postfix[++pptr]=pop(stack,&top);

    printf("%s\n",postfix);}