Unix&CD

Embed Size (px)

Citation preview

  • 7/31/2019 Unix&CD

    1/73

    DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

    LAB MANUAL

    UNIX PROGRAMMING AND COMPILER DESIGN

    [ ]

    Guru Nanak

    Engineering CollegeIbrahimpatnam, R R District 501 506 (A. P.)

    Document No:GNEC/CSE/LAB

    MANUAL/UNIX &CD [ ]

    Date of Issue: Compiled By: Authorized By

    HOD CSEVersion : 1.1 Date of Revision: Verified By:

    1

  • 7/31/2019 Unix&CD

    2/73

    INDEX

    S.No Contents Page.no

    1 Lab Objective 3

    2 Introduction About Lab4-5

    3 Guidelines to Students 6-7

    4

    List of Lab Exercises

    4.1 Syllabus Programs (JNTU)

    4.2 Additional and Advanced Programs

    8

    5 Description about UNIX commands 9-17

    6 Solutions for Unix Programs 18-48

    7 Solutions for Compiler Design Programs 54-66

    8 References 67

    2

  • 7/31/2019 Unix&CD

    3/73

    LAB OBJECTIVE

    Upon successful completion of this Lab the student will be able to:

    1. Demonstrate how to use the following Bourne Shell commands: cat,grep, ls, more, ps, chmod, finger, ftp, etc.

    2. Use the following Bourne Shell constructs: test, if then, if then else, if then elif, for, while, until, and case.3. Learn tracing mechanisms (for debugging), user variables, BourneShell

    variables, read-only variables, positional parameters, reading input to aBourneShell script, command substitution, comments, and exportingvariables. In addition, test on numeric values, test on file type, and teston character strings are covered.

    4. Copy, move, and delete files and directories

    5. Write moderately complex Shell scripts.

    6. Make a Shell script executable.

    7. Create a ".profile" script to customize the user environment.

    8. Use advanced features of File Transfer Protocol (FTP)

    9. Compile source code into object and executable modules.

    10. Execute programs written in c under UNIX environment

    3

  • 7/31/2019 Unix&CD

    4/73

    INTRODUCTION ABOUT LAB

    There are 66 systems ( Compaq Presario ) installed in thisLab. Their configurations are as follows :

    Processor : AMD Athelon 1.67 GH z

    RAM : 256 MB

    Hard Disk : 40 GB

    Mouse : Optical Mouse

    Network Interface card : Present

    Software

    All systems are configured in DUAL BOOT mode i.e, Students can

    boot from Windows XP or Linux as per their lab requirement.This is very useful for students because they are familiar withdifferent Operating Systems so that they can execute their

    programs in different programming environments.

    Each student has a separate login for database access

    Oracle 9i client version is installed in all systems. On the server,account for each student has been created.

    This is very useful because students can save their work

    ( scenarios, pl/sql programs, data related projects ,etc) in their ownaccounts. Each student work is safe and secure from other students.

    Latest Technologies like DOT NET and J2EE are installed insome systems. Before submitting their final project, they can startdoing mini project from 2 nd year onwards.

    4

  • 7/31/2019 Unix&CD

    5/73

    MASM ( Macro Assembler ) is installed in all the systems

    Students can execute their assembly language programs usingMASM. MASM is very useful students because when theyexecute their programs they can see contents of ProcessorRegisters and how each instruction is being executed in theCPU .

    Rational Rose Software is installed in some systems

    Using this software, students can depict UML diagrams of their projects.

    Softwares installed : C, C++, JDK1.5, MASM, OFFICE-XP,J2EE and DOT NET, Rational Rose.

    Systems are provided for students in the 1:1 ratio.

    Systems are assigned numbers and same system is allotted forstudents when they do the lab.

    5

  • 7/31/2019 Unix&CD

    6/73

    Guidelines to Students

    How to Run Shell Scripts

    There are two ways you can execute your shell scripts. Once you have created ascript file:

    Method 1Pass the file as an argument to the shell that you want to interpret your script.

    Step 1 : create the script using vi, ex or edFor example, the script file show has the following lines

    echo Here is the date and timedate

    Step 2 : To run the script, pass the filename as an argument to the sh (shell )

    $ sh showHere is the date and timeSat jun 03 13:40:15 PST 2006

    Method 2: Make your script executable using the chmod command.

    When we create a file, by default it is created with read and write permissionturned on and execute permission turned off. A file can be made executableusing chmod.

    Step 1 : create the script using vi, ex or ed

    For example, the script file show has the following lines

    echo Here is the date and timedate

    Step 2 : Make the file executable

    6

  • 7/31/2019 Unix&CD

    7/73

    $ chmod u+x script_file$ chmod u+x show

    Step 3 : To run the script, just type the filename

    $ showHere is the date and timeSat jun 03 13:40:15 PST 2006

    How to run C programs

    Step 1 : Use an editor, such as vi, ex, or ed to write the program. The name of the file containing the program should end in .c.

    For example, the file show.c contains the following lines :

    main(){

    printf( welcome to GNEC );}

    Step 2 : Submit the file to CC ( the C Compiler )

    $ cc show.c

    If the program is okay, the compiled version is placed in a file calleda.out

    Step 3 : To run the program, type a.out

    $ a.out

    Welcome to GNEC

    7

  • 7/31/2019 Unix&CD

    8/73

    List of Lab Exercises

    Syllabus Programs ( JNTU )

    S.No Programs PageNo

    1 Write a shell script to generate a multiplication table 182 Write a shell script that copies multiple files to a directory. 19-203 Write a shell script that counts the number of lines and words

    present in a given file.21-22

    4 Write a shell script that displays the list of all files in a givendirectory.

    23-24

    5 Write a shell script (small calculator) thatadds,subtracts,multiplies and divides the given two integers.

    There are division options: one returns the quotient and theother returns remainder.

    The script requires 3 arguments: The operation to be used

    and two integer numbers.The options are add(-a),subtract(-s),multiply(-m),quotient(-

    c) and remainder)-r).

    25-26

    6 Write a Shell Script to reverse the rows and columns of amatrix

    27-28

    7 Write a C program that counts the number of blanks in a textfile.

    a) Using standard I/Ob) Using system calls.

    29

    8 Implement in C the following Unix commands using systemcalls.

    a) catb) lsc) mv

    30-32

    9 Write a program that takes one or more file/directory names ascommand line input and reports the following information onfile:

    33-34

    8

  • 7/31/2019 Unix&CD

    9/73

  • 7/31/2019 Unix&CD

    10/73

    your current position in the UNIX filesystem.

    Examples pwd

    There are no options (or arguments) with the "pwd" command.

    It is simply used to report your current working directory.Command ls

    Syntax ls [options] [names]

    Description "ls" stands for list. It is used to list information aboutfiles and directories.

    Examples ls

    This is the basic "ls" command, with no options. It provides avery basic listing of the files in your current working directory.Filenames beginning with a decimal are considered hiddenfiles, and they are not shown.

    ls -a

    The -a option tells the ls command to report information aboutall files, including hidden files.

    ls -l

    The -l option tells the "ls" command to provide a long listing of information about the files and directories it reports. The longlisting will provide important information about file

    permissions, user and group ownership, file size, and creationdate.

    ls -al

    This command provides a long listing of information about all files in the current directory. It combines the functionality of the -a and -l options. This is probably the most used version of the ls command .

    ls -al /usr This command lists long information about all files in the"/usr" directory.

    ls -alR /usr | more

    This command lists long information about all files in the

    10

  • 7/31/2019 Unix&CD

    11/73

    "/usr" directory, and all sub-directories of /usr. The -R optiontells the ls command to provide a recursive listing of all filesand sub-directories.

    ls -ld /usr

    Rather than list the files contained in the /usr directory, thiscommand lists information about the /usr directory itself (without generating a listing of the contents of /usr). This isvery useful when you want to check the permissions of thedirectory, and not the files the directory contains.

    Command mv

    Syntax mv [options] sources target

    Options -b backup files that are about to be overwritten or removed-i interactive mode; if dest exists, you'll be

    asked whether to overwrite the file

    Description The "mv" command is used to move and rename files.

    Examples mv Chapter1 Chapter1.bad

    This command renames the file "Chapter1" to the new name"Chapter1.bad".

    mv Chapter1 garbage

    This command renames the file "Chapter1" to the new name"garbage". (Notice that if "garbage" is a directory, "Chapter1"would be moved into that directory).

    mv Chapter1 /tmpThis command moves the file "Chapter1" into the directorynamed "/tmp".

    mv tmp tmp.old

    Assuming in this case that tmp is a directory, this examplerenames the directory tmp to the new name tmp.old.

    Command rm

    Syntax rm [options] files

    Options -d, --directory

    unlink FILE, even if it is a non-empty directory(super-user only)

    -f, --forceignore nonexistent files, never prompt

    11

  • 7/31/2019 Unix&CD

    12/73

    -i, --interactiveprompt before any removal

    -r, -R, --recursive

    remove the contents of directories recursively-v, --verbose

    explain what is being doneDescription The "rm" command is used to remove files and

    directories. (Warning - be very careful when removingfiles and directories!)

    Examples rm Chapter1.bad

    This command deletes the file named "Chapter1.bad"(assuming you have permission to delete this file).

    rm Chapter1 Chapter2 Chapter3

    This command deletes the files named "Chapter1", "Chapter2",and "Chapter3".

    rm -i Chapter1 Chapter2 Chapter3

    This command prompts you before deleting any of the threefiles specified. The -i option stands for inquire . You mustanswer y (for yes) for each file you really want to delete. Thiscan be a safer way to delete files.

    rm *.html

    This command deletes all files in the current directory whosefilename ends with the characters ".html".

    rm index*

    This command deletes all files in the current directory whosefilename begins with the characters "index".

    rm -r new-novel

    This command deletes the directory named "new-novel". Thisdirectory, and all of its' contents, are erased from the disk,including any sub-directories and files.

    Command cp

    Syntax cp [options] file1 file2

    cp [options] files directory

    Options -b backup files that are about to be overwritten or removed-i interactive mode; if dest exists, you'll be asked whether to

    12

  • 7/31/2019 Unix&CD

    13/73

    overwrite the file-p preserves the original file's ownership,

    group, permissions, and timestamp

    Description The "cp" command is used to copy files and directories.

    Note that when using the cp command, you must alwaysspecify both the source and destination of the file(s) to becopied.

    Examples cp .profile .profile.bak

    This command copies your ".profile" to a file named".profile.bak".

    cp /usr/fred/Chapter1 .

    This command copies the file named "Chapter1" in the"/usr/fred" directory to the current directory. This exampleassumes that you have write permission in the currentdirectory.

    cp /usr/fred/Chapter1 /usr/mary

    This command copies the "Chapter1" file in "/usr/fred" to thedirectory named "/usr/mary". This example assumes that youhave write permission in the "/usr/mary" directory.

    Command grep

    Syntax grep [options] regular expression [files]

    Options -i case-insensitive search-n show the line# along with the matched line-v invert match, e.g. find all lines that do NOT match-w match entire words, rather than

    substrings

    Description Think of the "grep" command as a "search" command(most people wish it was named "search"). It is used tosearch for text strings within one or more files.

    Examples grep 'fred' /etc/passwd

    This command searches for all occurrences of the text string'fred' within the "/etc/passwd" file. It will find and print (on thescreen) all of the lines in this file that contain the text string

    'fred', including lines that contain usernames like "fred" - andalso "alfred".

    grep ' fred' /etc/passwd

    This command searches for all occurrences of the text string'fred' within the "/etc/passwd" file, but also requires that the "f"

    13

  • 7/31/2019 Unix&CD

    14/73

    in the name "fred" be in the first column of each record (that'swhat the caret character tells grep). Using this more-advancedsearch, a user named "alfred" would not be matched, becausethe letter "a" will be in the first column.

    grep 'joe' *This command searches for all occurrences of the text string'joe' within all files of the current directory.

    Command mkdir

    Syntax mkdir [options] directory name

    Description The "mkdir" command is used to create new directories(sub-directories).

    Examples mkdir tmp

    This command creates a new directory named "tmp" in your current directory. (This example assumes that you have the proper permissions to create a new sub-directory in your current working directory.)

    mkdir memos letters e-mail

    This command creates three new sub-directories (memos,letters, and e-mail) in the current directory.

    mkdir /usr/fred/tmp

    This command creates a new directory named "tmp" in thedirectory "/usr/fred". "tmp" is now a sub-directory of "/usr/fred". (This example assumes that you have the proper

    permissions to create a new directory in /usr/fred.)

    mkdir -p /home/joe/customer/acme

    This command creates a new directory named/home/joe/customer/acme, and creates any intermediatedirectories that are needed. If only /home/joe existed to beginwith, then the directory "customer" is created, and the directory"acme" is created inside of customer.

    Command rmdir

    Syntax rmdir [options] directories Description The "rm" command is used to remove files and

    directories. (Warning - be very careful when removingfiles and directories!)

    Examples rm Chapter1.bad

    14

  • 7/31/2019 Unix&CD

    15/73

    This command deletes the file named "Chapter1.bad"(assuming you have permission to delete this file).

    rm Chapter1 Chapter2 Chapter3

    This command deletes the files named "Chapter1", "Chapter2",and "Chapter3".

    rm -i Chapter1 Chapter2 Chapter3

    This command prompts you before deleting any of the threefiles specified. The -i option stands for inquire . You mustanswer y (for yes) for each file you really want to delete. Thiscan be a safer way to delete files.

    rm *.html

    This command deletes all files in the current directory whosefilename ends with the characters ".html".

    rm index*

    This command deletes all files in the current directory whosefilename begins with the characters "index".

    rm -r new-novel

    This command deletes the directory named "new-novel". Thisdirectory, and all of its' contents, are erased from the disk,including any sub-directories and files.

    Command cd, chdir

    Syntax cd [name of directory you want to move to] Description "cd" stands for change directory. It is the primary

    command for moving around the filesystem.

    Examples cd /usr

    This command moves you to the "/usr" directory. "/usr" becomes your current working directory.

    cd /usr/fred

    Moves you to the "/usr/fred" directory.

    cd /u*/f*Moves you to the "/usr/fred" directory - if this is the onlydirectory matching this wildcard pattern.

    cd

    Issuing the "cd" command without any arguments moves you

    15

  • 7/31/2019 Unix&CD

    16/73

    to your home directory.

    cd -

    Using the Korn shell, this command moves you back to your previous working directory. This is very useful when you're inthe middle of a project, and keep moving back-and-forth

    between two directories.Command kill

    Syntax kill [options] IDs

    Description kill ends one or more process IDs. In order to do this you mustown the process or be designated a privileged user. To find the

    process ID of a certain job use ps.

    Examples Command ps

    Syntax ps [options]

    Description The "ps" command (process statistics) lets you check thestatus of processes that are running on your Unix system.

    Examples ps

    The ps command by itself shows minimal information aboutthe processes you are running. Without any arguments, thiscommand will not show information about other processesrunning on the system.

    ps -f

    The -f argument tells ps to supply full information about the processes it displays. In this example, ps displays fullinformation about the processes you are running.

    ps -e

    The -e argument tells the ps command to show every processrunning on the system.

    ps -ef

    The -e and -f arguments are normally combined like this toshow full information about every process running on thesystem. This is probably the most often-used form of the ps

    16

    http://webmonkey.com/webmonkey/reference/unix_guide/ps.htmlhttp://webmonkey.com/webmonkey/reference/unix_guide/ps.html
  • 7/31/2019 Unix&CD

    17/73

    command.

    ps -ef | more

    Because the output normally scrolls off the screen, the outputof the ps -ef command is often piped into the more command.The more command lets you view one screenful of informationat a time.

    ps -fu fred

    This command shows full information about the processescurrently being run by the user named fred (the -u option letsyou specify a username).

    17

  • 7/31/2019 Unix&CD

    18/73

    1) Name of the Experiment:

    AIM: Write a shell script to generate a multiplication table.

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM:

    Step1: StartStep2: read nStep3: for i=1 to 10Step4: print n*iStep5: Stop

    Test Data:

    Valid Data Set: 6

    InValid Data Set: n should not 0

    Limiting Data Set: n should be -300 to +300

    Result

    1) Enter the number 4

    4*1=44*2=84*3=124*4=164*5=204*6=244*7=28

    18

  • 7/31/2019 Unix&CD

    19/73

    4*8=324*9=364*10=40

    Viva-Voce Questions

    1. Why * is proceeded by \ ?2. What are different types of shells?3. How to execute shell script?4. Explain syntax of for loop?5. How arithmetic operations are done in Shell?6. How to combine echo & read?

    2) Name of the Experiment

    AIM: Write a shell script that copies multiple files to a directory.

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM

    Step1: StartStep2: read dir1Step3: if (dir1==dir name)

    Print directory existesElsePrint directory not exists

    Step4: if step 3 is true thenStep5: Read file1

    If file1 is existsCopy the file1 into file2 and print The file copied to dir1

    directoryElse File is not exists

    Step6: Stop

    Test Data:

    Valid Data Set: Input should be a Directory name

    InValid Data Set: Not applicable

    19

  • 7/31/2019 Unix&CD

    20/73

    Limiting Data Set: Not applicable

    Result

    1) Enter Directory Name : GuruDirectory does not exist.

    2) Enter Directory Name: cseDirectory exist

    Enter file name to be copied and type quit KarunaFile copiedEnter file name to be copied and type quit RajaniFile copied

    Enter file name to be copied and type quit quit

    Viva-Voce Questions

    1. Explain syntax of while loop?2. How to check whether the given string is file or not?3. Which command is used for copying a file?4. Explain the syntax of command used for renaming the file?5. Which command is used to list files in Directory6. What vi stands for?

    20

  • 7/31/2019 Unix&CD

    21/73

    3) Name of the Experiment

    AIM: Write a shell script that counts the number of lines and words present ina given file.

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM

    Step1: StartStep2: read a file1Step3: if file1 exists

    Print no. of lines are.. lPrint no. of words are wPrint no. of characters are.. c

    Step4: elsePrint file1 is not exists

    Step5: Stop

    Test Data:

    21

  • 7/31/2019 Unix&CD

    22/73

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set Not applicableResult

    1) Enter file name DemoThis is demoFile to know

    Number of wordsCharacters and line

    Lines : 4Words : 13

    Characters: 652) Enter file name engineer

    Guru Nanak Engineering CollegeLines : 1Words : 4Characters: 30

    Viva-Voce Questions

    1. Which command is used for display file?2. Which command is used to count the no. of lines?3. Explain the syntax of wc?4. What is shell?5. Explain the syntax of if loop?6. What is vi editor?

    22

  • 7/31/2019 Unix&CD

    23/73

    4) Name of the Experiment

    AIM: Write a shell script that displays the list of all files in a given directory.

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM:

    Step1: StartStep2: read dir1

    23

  • 7/31/2019 Unix&CD

    24/73

    Step3: if (dir1==dir name)Print Directory exists

    Step4: if step3 is trueRead file1

    Step5: if(-r dir1/file1) thenPrint readStep6: else if (-w dir1/file1) then

    Print writeStep7: else if(-x dir1/file1) then

    Print ExecuteStep8: else

    Print file1 is not existsStep9: Stop

    Test Data:

    Valid Data Set: Input should be a directory name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    ResultEnter the directory name guru

    Directory exists-a file

    ReadWriteExecute

    -b file

    24

  • 7/31/2019 Unix&CD

    25/73

  • 7/31/2019 Unix&CD

    26/73

    numbers.The options are add (-a), subtract (-s), multiply (-m), quotient (-c) and

    remainder)-r).

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHMStep1: StartStep2: read a, b, option

    Step3: if (option==1) thenResult=a+bPrint result

    Step4: if (option==2) thenResult=a-bPrint result

    Step5: if(option==3) thenResult=a*bPrint result

    Step6: if(option==4) thenResult=a%bPrint result

    Step7: if(option==5)Result=a/bPrint resultElse if Print Invalid operation

    Step8: Stop

    Test Data:

    Valid Data Set: 5 8

    InValid Data Set: 5 0

    Limiting Data Set: the second number should not beZero

    26

  • 7/31/2019 Unix&CD

    27/73

    Result

    Enter two numbers: 4 5Enter the choice 3The result is 20

    Enter two numbers: 8 2Enter the choice 5The result is 4

    Viva-Voce Questions

    1. Explain the syntax of switch case statement?2. Which command is used for linking a file?3. What do you mean by linking a file?4. Which command is used for displaying time?5. Which command is used to search a pattern in given file?6. Explain syntax of cat command?

    27

  • 7/31/2019 Unix&CD

    28/73

    6) Name of the Experiment

    AIM : Write a shell script to reverse the rows and columns of a matrix.

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk ALGORITHM

    Step1: StartStep2: read m1[],m2[],a, bStep3: for i=1 to a

    for j=1 to b print m1[i][j]

    Step4: for i=1 to bfor j=1 to am2[i][j]=m1[i][j]

    Step5: print m2[i][j]Step6: Stop

    Test Data:

    Valid Data Set: 1 23 4

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result

    Enter the matrix size 2 3

    28

  • 7/31/2019 Unix&CD

    29/73

    Enter the matrix 1 2 34 5 6

    The resultant matrix is 1 4

    2 53 6

    Viva-Voce Questions

    1. What are the three modes of vi editor?2. Which commands are used to perform copy & paste operations in vi

    editor?3. What is kernel?4. What are the various shell responsibilities?5. What are the various shell commands?

    29

  • 7/31/2019 Unix&CD

    30/73

    7) Name of the ExperimentAIM: Write a C program that counts the number of blanks in a text file.

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM:

    Step1: StartStep2: read fiel1, char ch, int scStep3: initiate sc to 0 i.e sc=0Step4: if(file1==NULL) then

    Print unable to open a fileStep5: else if Step6: While end of file

    ch=fgetc(file1)Step7: if(ch== )

    sc=sc+1Step8: print no. of spaces are scStep9: Stop

    Test Data:

    Valid Data Set: Input should be a file name

    30

  • 7/31/2019 Unix&CD

    31/73

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result

    1) $ cc blank.c$ ./a.out blank.c

    Spaces are 11Viva-Voce Questions

    1. What is the procedure to create & execute C program in Unix?2. What is system calls?3. Explain the syntax of open() & read() system calls?

    4. What is the purpose of lseek system call?5. Where the object code of c program is getting saved in unix?

    8) Name of the Experiment:

    AIM: Implement in C the following Unix commands using system calls.a) catb) lsc) mv

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM:

    (cat system call)

    Step1: StartStep2: read int fd,i

    char ch[1]Step3: if(argc

  • 7/31/2019 Unix&CD

    32/73

    Print argv[1] is not existsElsePrint Contents of the file are argv[1]

    Step6: while(read(fd,ch,1)>0)

    Print (ch [0])Step7: Stop

    (ls system call)

    Step1: startStep2: create a structure dinfoStep3: read dpStep4: if (argcd_name

    Step6: Stop

    (My system calls)

    Step1: StartStep2: read a file *fpStep3: if(argc

  • 7/31/2019 Unix&CD

    33/73

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result:

    Implementing cat command

    1) $ cc cat.c$ ./a.out oneContents of the file one is: Welcome to Unix Programming

    Implementing ls command

    $ cc ls.c$ ./a.out kal.. .File 1Kal2.sh

    Implementing mv command$ cc mv.c$ ./a.out b cFile moved or renamed successfully

    Viva-Voce Questions:

    1. Explain opendir() system call?2. What are the various options that can be used with ls command?3. Explain different uses of cat command?4. What is the purpose of mv command?5. What are the various elements of different structure?

    33

  • 7/31/2019 Unix&CD

    34/73

  • 7/31/2019 Unix&CD

    35/73

    ALGORITHM

    Step1: Start

    Step2: read a FILE *streamint buffer_character Step3: stream= fopen(test,r)Step4: if(stream==(FILE *))0)

    Print (stderr,Error opening file(printed to standard error))Step5: while ((buffer_character=getc(stream))!=EOF)Step6: write the character to standard out and check for errorsStep7: if((putc(buffer_character,stdout))==EOF)

    Print (stderr,Error writing to standard out.(printed to standarderror))Step8: if(fclose(stream))==EOF)

    Print(stderr,Error closing stream.(printed to standard error))Step9: stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result:

    cc file inf.c./a.out file.inf.cSize 320Type and permission : 10064

    No.of links : 1Access time . Apr 20 10:45:35

    Viva-Voce Questions:

    1. What is inode table? What all information it consist of regarding files?

    35

  • 7/31/2019 Unix&CD

    36/73

    2. How to know the inode has no. of a particular file?3. How we can access the inode table?4. Explain the syntax of stat() & fstat() system calls?5. What is the difference between stat() & fstat()?

    6. What are the various elements of stat structure?

    10) Name of the Experiment:

    AIM: C program that illustrates how to execute two commands concurrentlywith a command pipe

    36

  • 7/31/2019 Unix&CD

    37/73

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM

    Step1: StartStep2: read int i,pid

    static char path[]=/u/test2Step3: fork a child process

    pid=fork()Step4: if(pid==0)chdir(path)

    Step5: for i=0 to 30000sub2()i++ /*30000 calls to sub2 in child profile*/

    Step6: else /*parent process.leave gmon.out in current directory*/for i=0 to 1000sub1(pid)i++ /*1000 calls to sub1 in parent profile*/

    Step7: read int sub1(pid) /*silly little function called by parent 1000times

    int pid,iStep8: print (Im the parent ,child pid )Step9: print(Im the child)Step10:stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    37

  • 7/31/2019 Unix&CD

    38/73

    Result:

    sh-2.00$ fork Process 19643 about to fork a child.

    PID TT S TIME COMMAND19632 p1 S 0:00.36 -bash (bash)19638 p1 S + 0:00.07 script showem19640 p1 S + 0:00.03 script showem19641 p2 S 0:00.15 sh -is19643 p2 S + 0:00.04 fork 19644 p2 S + 0:00.01 fork 19645 p2 S + 0:00.04 sh -c ps19646 p2 R + 0:00.04 sh -c ps19648 p2 R + 0:00.00 sh -c ps

    PID TT S TIME COMMAND

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbb19632 p1 S 0:00.36 -bash (bash)19638 p1 S + 0:00.07 script showem19640 p1 R + 0:00.03 script showem19641 p2 S 0:00.15 sh -is19643 p2 S + 0:00.04 fork 19644 p2 S + 0:00.01 fork 19645 p2 R + 0:00.04 sh -c ps19646 p2 S + 0:00.04 sh -c psCreated child process 19644.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    38

  • 7/31/2019 Unix&CD

    39/73

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

    aaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaash-2.00$ exitexit

    Viva-Voce Questions;

    1. What is the pipeline? Explain with Example?2. $who | wc l what will be the output of this command?3. Pipeline is example of which redirection?4. What is input & output of redirection?5. What is the difference between the file and kernel?

    39

  • 7/31/2019 Unix&CD

    40/73

    11) Name of the Experiment:

    AIM: Write a program that illustrates the creation of child process using fork system call.

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM

    Step1: StartStep2: read pid_t pidStep3: pid=fork()Step4: switch(pid)Step5: if case = -1

    Print Fork calledElse if case= 0Print It is child process

    Step6: elsePrint It is parent process : CHILD PID is pid

    Step7: Stop

    40

  • 7/31/2019 Unix&CD

    41/73

    Test Data:

    Valid Data Set: Input should be a file nameInValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result:$ cc fork.c$ ./a.out fork.c

    It is a child processIt is parent process : child pid is : 16281

    Viva Voce Questions:

    1. What is process?2. What are the various attributes of process & when they will be saved?3. What is the purpose of fork() system call?explain with syntax?4. What is zombie process?5. What is chioldprocess & parent process?what are its pids?6. What is the purpose of esec & wait system call?

    41

  • 7/31/2019 Unix&CD

    42/73

  • 7/31/2019 Unix&CD

    43/73

  • 7/31/2019 Unix&CD

    44/73

    Step3: create a union semunStep4: if((key=ftok(semdemo.c,J))==-1)

    Perror(ftok)Step5: create a semaphore set with 1 semaphore

    If((semid=semget(key,1,0666|IPC_CREAT))==-1)Perror(semget)Step6: initiliaze semaphore #0 to 1

    Arg.val=1Step7: if(semctl(semid,0,SETVAL,arg)==-1)

    Perror(semctl)Step8: Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result

    $ cc fork.c$ ./a.out fork.cIt is a child process

    It is parent process : child pid is : 16281Viva-Voce Questions:

    1. What is semaphore?2. What are the two types of locking ?Explain difference?3. What is file locking & record locking?4. Which function is used for file locking explain with syntax?5. Explain fcntl function used for record locking?

    14) Name of the Experiment:

    AIM: C Program for Inter Process Communication

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    44

  • 7/31/2019 Unix&CD

    45/73

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHMStep1: Start

    Step2: create struct sembuf sopint full ,empty,mutexStep3: struct msg

    read long mtypechar s[15]Pmsg,cmsg

    Step4: create the function for Producer()read int item=0

    Step5: while(item!=0)Produce-item(item)down(empty)

    down(mutex)enter-item(item)up(mutex)up(full)item=(item+1) %10

    Step6: create the function for Consumer()Read int item=0

    Step7: while(item!=0)down=fulldown(mutex)remove-item(item)up(mutex)up(empty)consume-item(item)item=(item+1)%10

    Step8: produce-item(int I)int mquid;sleep(1)

    print enter data for item no Iread Pmsg.sPmsg.mtype=5

    Step9: enter-item(int I)int mqidmqid=msgget((key-t)25,ipc-CREAT:0644)msgnd(mqid,&pmsg,sizeof(pmsg.s)0)

    print item writtenStep10:down(int semid)

    sop.sem-num=0sop.sem-op=-1

    45

  • 7/31/2019 Unix&CD

    46/73

    sop.sem-flg=0semop(semid,&sop,1)

    Step11:up(int semid)sop.em-num=0

    sop.op=-1sop.flag=0semop(semid,&sop,1)

    Step12:remove-item(int I)int mqidmqid=msgget((key-t)25,IPC-CREATE:0644)msgrcv(mqid,&cmsg,sizeof(cmsg.s),5,0)

    print item read from queueStep13:Consume-item(int I)

    Print item value is I,cmsg.sStep14:/*main program*/

    read pid,mqidStep15:mutex=semget(ckey-t)27,I,IPC-CREAT:0644)Step16:semct 1(mutex,0,SETVAL,1)Step17:empty=(semget(ckey-t)28,I,IPC-CREAT:0644)Step18:full=semget(ckey-t)29,I,IPC-CREAT:0644)Step19:sem1(full,0,STEVAL,0)Step20:mqid=msgget(key-t)25,IPC-CREAT:0644)Step21:pid=fork()Step22:if(pid==0)

    Execute Consumer() functionElseExecute Producer() function

    Step23:Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    46

  • 7/31/2019 Unix&CD

    47/73

    Result:

    Viva-Voce Questions:

    1. What is the two types of semaphores?2. What is semget,semop,semctl functions?3. What is producer,consumer problem?4. How IPC is performed using pipe?5. How pipe is created ?Expalin with example?

    47

  • 7/31/2019 Unix&CD

    48/73

    15) Name of the Experiment:

    AIM: creating and sending to a simple message queue

    S/W & H/W Requirements:

    S/W: Office-XP, Turbo C.

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM

    Step1: StartStep2: read FILE *fp1, *fp2, *fp3, *fp4, *fopen()float i ,y1,y2,y3,y4

    Step3: /* open files which will store plot data */if ( ((fp1 = fopen("plot11.dat","w")) == NULL) ||((fp2 = fopen("plot12.dat","w")) == NULL) ||((fp3 = fopen("plot21.dat","w")) == NULL) ||((fp4 = fopen("plot22.dat","w")) == NULL) )

    Print Error can't open one or more data files Step4: signal(SIGINT,quit)Step5: StartPlot()Step6: y1 = 0.5Step7: srand48(1)Step8: i=0iStep9: i+=0.01)Step10:y2 = (float) drand48()Step11:if (i == 0.0)

    y3 = 0.0elsey3 = sin(DEG_TO_RAD(1.0/i))y4 = sin(DEG_TO_RAD(i))

    Step12: /* load files */

    print(fp1,"%f %f\n",i,y1)print(fp2,"%f %f\n",i,y2)print(fp3,"%f %f\n",i,y3)print(fp4,"%f %f\n",i,y4)

    Step13:/* reads up to data file */

    48

  • 7/31/2019 Unix&CD

    49/73

    flush(fp1)flush(fp2)flush(fp3)flush(fp4)

    Step14: /* plot graph */PlotOne()usleep(250)

    void quit()Step15: print caught: Shutting down pipesStep16: StopPlot()Step17: print closing data files

    fclose(fp1)fclose(fp2)fclose(fp3)

    fclose(fp4) Step18: print deleting data filesStep19: RemoveDat()Step20: Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result:

    Enter files: A B C DCaught :Shutting down pipesClosing data files

    49

  • 7/31/2019 Unix&CD

    50/73

  • 7/31/2019 Unix&CD

    51/73

    Step5: print stderr, "\nmsgget: Calling msgget(%#lx,\%#o)\n",key,msgflg

    Step6: if ((msqid = msgget(key, msgflg )) < 0) perror("msgget")else

    print stderr,"msgget: msgget succeeded: msqid = %d\n", msqid)Step7: /* We'll send message type 1 */

    sbuf.mtype = 1 Step8: printstderr,"msgget: msgget succeeded: msqid = %d\n", msqid)Step9: strcpy(sbuf.mtext, "Did you get this?")

    Step10: printstderr,"msgget: msgget succeeded: msqid = %d\n", msqid)

    buf_length = strlen(sbuf.mtext) + 1

    Step11: /*Send a message. */ if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) {print %d, %d, %s, %d\n", msqid,sbuf.mtype,sbuf.mtext,

    buf_length)perror("msgsnd")

    else print Message: \"%s\" Sent\n", sbuf.mtext

    Step12:Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result:

    Enter some text: HelloEnter some text: How r uEnter some text: Today

    You Wrote: HelloYou Wrote: How r u

    51

  • 7/31/2019 Unix&CD

    52/73

    You Wrote: Today

    Viva-Voce Questions:

    1. How IPC is performed using message queue?2. What are various message system calls?3. What are various message operations?4. Explain message passing with example?5. What is signal? What are various signal functions?

    LAB OBJECTIVE

    The language Processors comprises assemblers, compilers and interpreters. Itdeals with the recognition the translation, and the execution of formallanguages It is closely related to compiler construction.

    Students will gain the knowledge of

    Lexical Analysis for decomposing a character stream into lexical units Syntax analysis for recovering context-free structure from an input

    stream, error correction Semantic analysis for enforcing non-context-free requirements,attribute grammars.

    Semantic definition, for describing the meaning of a phrase (we rely oninterpretive definitions)

    Implementation of programming concepts, control structures

    52

  • 7/31/2019 Unix&CD

    53/73

    Data representation, implementation of data structures Partial evaluation, for removing interpretation overhead Code generation: instruction selection, register allocation Further semantic analysis: document validation , type checking.

    PART B

    To provide an understanding of the language translation peculiarities bydesigning a complete translator for a mini language.Consider the following mini language, a simple procedural high-level language,only operating on integer data, with a syntax looking vaguely like a simple Ccrossed with Pascal. The syntax of the language is defined by the followingBNF grammar

    ::= ::= { }| {} ::= int ;

    ::= I , ::= I [ ] ::= I ;

    53

  • 7/31/2019 Unix&CD

    54/73

    ::= I I I I I ::= =

    I [ ] = ::= if then else endif

    I if then endif ::= while do enddo ::= print ( )

    ::= 1 1 ::= ::= < I = I > I != ::= + 1-

    ::= I ::= ' 1/ ::= I 1 [ ]I ( )

    ::= 1 ::= I ::= I

    ::= alblcldlelflglhlililklllmlnlolplqlrlsltlulvlwlxlYlz ::= 0|1|2|3|4|5|6|7|8|9|

    has the obvious meaning

    Comments (zero or more characters enclosed between the standard C/Java-stylecomment brackets / can be inserted. The language has rudimentary support for 1-dimensional arrays. The declaration a[31 declares an array of three elements,referenced as a[O], a[1] and a[2]. Note also that you should worry about thescoping of names.

    A simple program written in this language is:{ int a[3],t1,t2;t1=2;a[0]=1; a[1]=2; a[t1]=3;t2=-(a[2]+t1*6)/(a[2]-t1);

    if t2>5 thenprint(t2);

    else {int t3;t3=99;t2=-25;

    54

  • 7/31/2019 Unix&CD

    55/73

  • 7/31/2019 Unix&CD

    56/73

    stores the value in register R to variable V.OUT R outputs the value in register R.

    NEG R

    negates the value in register R.ADDA,R adds the value specified by A to register R, leaving the result in register R.SUB A,R subtracts the value specified by A from register R, leaving the result in register R.MULA, R multiplies the value specified by A by register R, leaving the result in register R.DIV A, R divides register R by the value specified by A, leaving the result in register R.

    JMP LCauses an unconditional jump to the instruction with the label L.JEQ R, L

    jumps to the instruction with the label L if the value in register R is zero.JNE R,l

    jumps to the instruction with the label L if the value in register R is not zero.JGE R,l

    jumps to the instruction with the label L if the value in register R is greater thanor equal to zero.

    JGT R,L jumps to the instruction with the label L if the value in register R is greater thanzero . . E JLE R,L

    jumps to the instruction with the label L if the value in register R is less than or equal to zero.JLT R,L

    jumps to the instruction with the label L if the value in register R is less thanzero.

    NOPis an instruction with no effect. It can be tagged by a label.STOPstops execution of the machine. All programs should terminate by executing aSTOP instruction.

    56

  • 7/31/2019 Unix&CD

    57/73

    Syllabus Programs

    S.No Name of the Program PageNo

    1 Design a Lexical analyzer. The lexical analyzer should ignore redundant stabs and new lines. It should also ignore comments. Although the syntaxspecification s that identifiers can be arbitrarily long, you may restrict thelength to some reasonable Value.

    54-56

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

    57-58

    3 Design Predictive Parser for the given language59-60

    4 Design LALR bottom up parser for the above language61-62

    5 Convert the BNF rules into YACC form and write code to generate abstractsyntax tree

    63-64

    6 Write program to generate machine code from the abstract syntax treegenerated by the Parser .The following instruction set may considered astarget code.

    65-66

    57

  • 7/31/2019 Unix&CD

    58/73

    1) Name of the Experiment:

    AIM: Design a Lexical analyzer. The lexical analyzer should ignore redundants tabs and new lines. It should also ignore comments. Although the syntaxspecification s that identifiers can be arbitrarily long, you may restrict thelength to some reasonable Value.

    S/W & H/W Requirements:S/W: Yet Another Compiler to Compiler (YACC) Compiler, Office XP,

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM:

    We make use of two functions.look up() it takes string as argument and checks its presence in the symboltable. If the string is found then returns the address else it returns NULL .insert() it takes string as its argument and the same is inserted into the symboltable and the corresponding address is returned.

    Step1: StartStep2: function scan

    lexbuf[50] of char tokenvalue[10]

    beginstore scanned char in cif c blank or tab,then

    do nothingelse if c is \n,thenline_number :=line_number=1else if c is a digit

    token value:=value of the digit and successive digitsreturn tokentype

    58

  • 7/31/2019 Unix&CD

    59/73

    Step3: p:=lookup(lexbuf)if p:=NULL, then

    p:=insert(lexbuf,id)token value:=lexbuf

    return(attribute from symboltable)elsetokenvalue:=NULLreturn(NULL) end

    Step4: Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result

    INPUT file xx.txt{int t1,t2t1=2t2=t1*3/2;if t2>5 then

    print(t2);else{int t3;t3=99;t2=-25

    print(-t1+t2+t3);}End if

    59

  • 7/31/2019 Unix&CD

    60/73

    OUTPUT

    SOB elseint SOB

    ID intSEPE IDID ENDSTENDST IDID ASSIGNASSIGN NUMENDST IDID ASSIGNASSIGN SUBOPID NUMMULOP ENDST

    DIVOP OPENPRAENDST SUBOPIf IDID ADDOPGT ID

    NUM MULOPThen ID

    print CLOSEPRAOPENPRA ENDSTID EOBCLOSEPRA endif ENDST

    Viva-Voce Questions

    1. What is lexical analyzer?2. Which compiler is used for lexical analyzer?3. What is YACC?4. What is the output of Lexical analyzer?5. What is LEX source Program?

    60

  • 7/31/2019 Unix&CD

    61/73

    2) Name of the Experiment:

    AIM: Implement the lexical analyzer using JLex, flex or lex other lexicalanalyzer generating tools.

    S/W & H/W Requirements:

    S/W: Yet Another Compiler to Compiler (YACC) Compiler, Office XP,

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM:

    Step1: StartStep2: Declare the declarations for the given language tokens like digit,

    alphabet, white space, delimiters, etc.digit[0-9]letter[A-Z a-z]delim[\t\n]

    61

  • 7/31/2019 Unix&CD

    62/73

    W${delim}+ID{(letter)(letter/digit)}+Integer {digit}+% %{ws} {print (SpecialCharacters)}

    {ID} {print(Identifiers)}{digit} {print(\n Integer)}if {printf(keyword)}else {print(keyword)}& & {print(logoical operators)}>{print(logoical operators)}

  • 7/31/2019 Unix&CD

    63/73

    Viva-Voce Questions

    1. What is Parsing?2. Construct the parsing table for the given?

    S1 iC+SS1|aS1 eS1|C b

    3. What is Token?

    4. What is Jlex?5. What is Flex?

    3) Name of the Experiment

    AIM: Design Predictive Parser for the given language

    S/W & H/W Requirements:

    S/W: Yet Another Compiler to Compiler (YACC) Compiler, Office XP,

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    63

  • 7/31/2019 Unix&CD

    64/73

    ALGORITHM

    Step1: StartStep2: declare w[10] as char and Z as an array

    Step3: enter the string with $ at the endStep4: if (A(w[z]) then increment z and check for (B(w[z])) and if satisfies increment z and check for d if d is present thenincrement and check for (D(w[z]))

    Step5: if step 4 is satisfied then the string is acceptedElse string is not

    Step6: give for the grammer A-> bc/ab in the loop A(int k)Step7: Describe the grammer b->c/d in the loop B (int k)Step8: Similarly describe the grammer D->d/abcdStep9: if steps7,8,9 are satisfied accordingly string is accepted

    Else string is not accepted

    Step10: Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result

    INPUT file aa.txt{int a, ba[10];a=a*a;

    b=a*b;if a

  • 7/31/2019 Unix&CD

    65/73

    Viva-Voce Questions

    1. What is Predictive parser?2. How many types of analysis can we do using Parser?3. What is Recursive Decent Parser?4. How many types of Parsers are there?5. What is LR Parser?

    4) Name of the Experiment:

    AIM: Design LALR bottom up parser for the above language

    65

  • 7/31/2019 Unix&CD

    66/73

    S/W & H/W Requirements:

    S/W: Yet Another Compiler to Compiler (YACC) Compiler, Office

    XP,H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHM

    Step1: StartStep2: Initially the parser has s0 on the stack where s0 is the initial

    state and w$ is in buffer Step3: Set ip point to the first symbol of w$

    Step4: repeat forever, beginStep5: Let S be the state on top of the stack and a symbol pointed to byip

    Step6: If action [S, a] =shift S then beginPush S1 on to the top of the stack Advance ip to next input symbol

    Step7: Else if action [S, a], reduce A->B then beginPop 2* |B| symbols of the stack Let S1 be the state now on the top of the stack

    Step8: Output the production A->BEnd

    Step9: else if action [S, a]=accepted, then returnElseError()End

    Step10: Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    66

  • 7/31/2019 Unix&CD

    67/73

    Result

    [ ] $ lex parser.l[ ] $ Yacc -d parser.y

    [ ] $ cc lex.yy.c y.tab.c -ll -ld[ ] $ ./a.out

    2+35.000

    Viva-Voce Questions

    1. What is LALR parsing?2. What is Shift reduced parser?3. What is the operations of Parser?4. What is the use of parsing table?5. What is bottom up parsing?

    67

  • 7/31/2019 Unix&CD

    68/73

    5) Name of the Experiment:

    AIM: Convert the BNF rules into YACC form and write code to generateabstract syntax tree

    S/W & H/W Requirements:

    S/W: Yet Another Compiler to Compiler (YACC) Compiler, Office XP,

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHMStep1: StartStep2: declare the declarations as a header file

    {include}Step3: token digitStep4: define the translations rules like line, expr, term, factor

    Line:exp \n {print(\n %d \n,$1)}Expr:expr+ term ($$=$1=$3}Term:term + factor($$ =$1*$3}Factor Factor:(enter) {$$ =$2)% %

    Step5: define the supporting C routinesStep6: Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result

    68

  • 7/31/2019 Unix&CD

    69/73

    [ ] $ lex int.l[ ] $ Yacc -d int y[ ] $ cc lex.yy.c y.tab.c -ll -ly

    [ ] $ ./a.out test.c

    POS Operator Arg1 Arg2 Result0 < a b to1 == to FALSE5

    2 + a b +13 = t1 a4 Goto 55 < a b t26 == t2 FALSE107 + a b +38 = t3 a9 GOTO 510

  • 7/31/2019 Unix&CD

    70/73

    6) Name of the Experiment: AIM: Write program to generate machine code from the abstract syntax treegenerated by the Parser .The following instruction set may considered as targetcode.

    S/W & H/W Requirements:

    S/W: Yet Another Compiler to Compiler (YACC) Compiler, Office XP,

    H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

    ALGORITHMStep1: StartStep2: for every three address statement of the form x=y op zStep3: beginStep4: Call getreg() to obtain the location L which the computation y

    op z should be performedStep5: Obtain the current location of the operand y by consulting its

    address descriptor ,and if the values of Y are currently both inthe memory location as well as in the register, then prefer theregister.If the value of y is not currently available in 1,thengenerate an instruction MOV y,l

    Step6: Generate the instruction OP Z,l and update the addressdescriptor of X to indicate that X is now available in l and inregister then update t\ its descriptor to indicate that it will

    70

  • 7/31/2019 Unix&CD

    71/73

    contain the run time value of xStep7: If the current values of y ad/or z are in register and we have no

    further use for them,and they are live at the end of the block,then after the register descriptor to indicate that after the

    execution of the statem,ent x=y op z,those registers will nolonger contain y and / or z.Step8: store all resultsStep9: Stop

    Test Data:

    Valid Data Set: Input should be a file name

    InValid Data Set: Not applicable

    Limiting Data Set: Not applicable

    Result

    Input file text1.txt

    =+ 1 2a 1 2a 2 3a 3 4+ a b c

    Output file target.txt

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

    LOAD a , R0

    71

  • 7/31/2019 Unix&CD

    72/73

    LOAD b , R1ADD R1 , R0SUB R0 , c

    Viva-Voce Questions

    1. What is target code?2. What is machine code?3. What is Cross compiler?4. Give the example for cross compiler?

    5. What is the difference between syntax & Semantics?

    References:

    BOOKS:

    Unix the ultimate Guide, Sumitabha das,TMHUnix networking programming, W.R Stevens Pearson/PHIAdvanced Programming in Unix environment, W.R Stevens Pearson/PHI

    Principles of Compiler Design, LMAN NarosaModem Compiler Implementation in C Andrew N.

    Appel,CambridgeUniversity Press

    Lex&yacc John R.Levine,TonyMason,Doug

    Brown,Orelly

    72

  • 7/31/2019 Unix&CD

    73/73

    WEBSITES:

    www.unix.com

    www.compilerdesign.comwww.lexicalanalyzer.com

    www.w3school.com