You are on page 1of 68

DEPARTMENT OF COMPUTER SCIENCE

AND ENGINEERING
LAB MANUAL
UNIX PROGRAMMING AND COMPILER DESIGN
[

Guru Nanak Engineering College


Ibrahimpatnam, R R District 501 506 (A. P.)
Document No:
GNEC/CSE/LAB
MANUAL/UNIX &
CD [
]
Version: 1.1

Date of Issue:

Compiled By:

Date of Revision:

Verified By:

Authorized By

HOD CSE

INDEX

S.No

Contents

Page.no

Lab Objective

Introduction About Lab

4-5

Guidelines to Students

6-7

List of Lab Exercises


8
4

4.1 Syllabus Programs (JNTU)


4.2 Additional and Advanced Programs

Description about UNIX commands

9-17

Solutions for Unix Programs

18-48

Solutions for Compiler Design Programs

54-66

References

67

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.

4.

Use the following Bourne Shell constructs: test, if then, if then else, if then elif,
for, while, until, and case.
Learn tracing mechanisms (for debugging), user variables, BourneShell variables,
read-only variables, positional parameters, reading input to a BourneShell script,
command substitution, comments, and exporting variables. In addition, test on
numeric values, test on file type, and test on character strings are covered.
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.

INTRODUCTION ABOUT LAB

There are 66 systems ( Compaq Presario ) installed in this Lab.


Their configurations are as follows :
Processor

AMD Athelon 1.67 GHz

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 with different
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 own accounts. Each student
work is safe and secure from other students.
Latest Technologies like DOT NET and J2EE are installed in some systems.
Before submitting their final project, they can start doing mini project from 2nd
year onwards.

MASM ( Macro Assembler ) is installed in all the systems

Students can execute their assembly language programs using MASM.


MASM is very useful students because when they execute their programs
they can see contents of Processor Registers and how each instruction is
being executed in the CPU.
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 for students when
they do the lab.

Guidelines to Students
How to Run Shell Scripts
There are two ways you can execute your shell scripts. Once you have created a script
file:
Method 1
Pass the file as an argument to the shell that you want to interpret your script.
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 time
date
Step 2 : To run the script, pass the filename as an argument to the sh (shell )
$ sh show
Here is the date and time
Sat 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 permission turned on
and execute permission turned off. A file can be made executable using 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 time
date
Step 2 : Make the file executable
$ chmod u+x script_file
6

$ chmod u+x show


Step 3 : To run the script, just type the filename
$ show
Here is the date and time
Sat 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 called a.out
Step 3 : To run the program, type a.out
$ a.out
Welcome to GNEC

List of Lab Exercises


Syllabus Programs ( JNTU )
S.No
1
2
3
4
5

6
7

10
11
12

Programs
Write a shell script to generate a multiplication table
Write a shell script that copies multiple files to a directory.
Write a shell script that counts the number of lines and words
present in a given file.
Write a shell script that displays the list of all files in a given
directory.
Write a shell script (small calculator) that
adds,subtracts,multiplies and divides the given two integers.
There are division options: one returns the quotient and
the other 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).
Write a Shell Script to reverse the rows and columns of a
matrix
Write a C program that counts the number of blanks in a text
file.
a) Using standard I/O
b) Using system calls.
Implement in C the following Unix commands using system
calls.
a) cat
b) ls
c) mv
Write a program that takes one or more file/directory names
as command line input and reports the following information
on file:
c) File type.
d) Number of
links.
e) Time of last access.
f) Read, Write
and Execute permissions.
C program that illustrates how to execute two commands
concurrently with a command pipe
Write a C program that illustrates the creation of child process
using fork system call.
Write a C Program that displays the real time of a day every

Page
No
18
19-20
21-22
23-24
25-26

27-28
29

30-32

33-34

35-37
38-39
40
8

13
14
15
16

60 seconds
C Program for File locking using semaphores
C Program for Inter Process Communication
creating and sending to a simple message queue
Write a C program tha illustrates the following.
g) Creating a message queue.
h) Writing to a message queue.
i) reading from a message queue.

41
42-44
45-46
47-48

Basic Unix commands

Command
CAT
Syntax
cat [argument] [specific file]
Description
Examples

cat" is short for concatenate. This command is used


to create, view and concatenate files.
cat /etc/passwd
This command displays the "/etc/passwd" file on your screen.
cat /etc/profile
This command displays the "/etc/profile" file on your screen.
Notice that some of the contents of this file may scroll off of
your screen.
cat file1 file2 file3 > file4
This command combines the contents of the first three files
into the fourth file.

Command
pwd
Syntax
pwd
Description
Examples

"pwd" stands for print working directory. It displays


your current position in the UNIX filesystem.
pwd
There are no options (or arguments) with the "pwd"
command. It is simply used to report your current working
directory.

Command
Syntax

ls
ls [options] [names]

Description
Examples

"ls" stands for list. It is used to list information about


files and directories.
ls
This is the basic "ls" command, with no options. It provides a
very basic listing of the files in your current working
directory. Filenames beginning with a decimal are considered
hidden files, and they are not shown.
ls -a
The -a option tells the ls command to report information about
all 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
long listing will provide important information about file
permissions, user and group ownership, file size, and creation
date.
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
"/usr" directory, and all sub-directories of /usr. The -R option
tells the ls command to provide a recursive listing of all files

10

and sub-directories.
ls -ld /usr
Rather than list the files contained in the /usr directory, this
command lists information about the /usr directory itself
(without generating a listing of the contents of /usr). This is
very useful when you want to check the permissions of the
directory, and not the files the directory contains.
Command
mv
Syntax
Options

mv [options] sources target


-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
Examples

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


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 /tmp
This command moves the file "Chapter1" into the directory
named "/tmp".
mv tmp tmp.old
Assuming in this case that tmp is a directory, this example
renames the directory tmp to the new name tmp.old.

Command
rm
Syntax
Options

rm [options] files
-d, --directory
unlink FILE, even if it is a non-empty directory
(super-user only)

11

-f, --force
ignore nonexistent files, never prompt
-i, --interactive
prompt before any removal
-r, -R, --recursive
remove the contents of directories recursively
-v, --verbose
explain what is being done
Description

Examples

The "rm" command is used to remove files and


directories. (Warning - be very careful when removing
files and directories!)
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 three
files specified. The -i option stands for inquire. You must
answer y (for yes) for each file you really want to delete. This
can be a safer way to delete files.
rm *.html
This command deletes all files in the current directory whose
filename ends with the characters ".html".
rm index*
This command deletes all files in the current directory whose
filename begins with the characters "index".
rm -r new-novel
This command deletes the directory named "new-novel". This
directory, and all of its' contents, are erased from the disk,
including any sub-directories and files.

12

Command
Syntax
Options

cp
cp [options] file1 file2
cp [options] files directory
-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
-p

Description

Examples

preserves the original file's ownership,


group, permissions, and timestamp

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


Note that when using the cp command, you must always
specify both the source and destination of the file(s) to be
copied.
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 example
assumes that you have write permission in the current
directory.
cp /usr/fred/Chapter1 /usr/mary
This command copies the "Chapter1" file in "/usr/fred" to the
directory named "/usr/mary". This example assumes that you
have write permission in the "/usr/mary" directory.

Command
grep
Syntax
Options

grep [options] regular expression [files]


-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
substrings

match entire words, rather than

Description

Examples

Think of the "grep" command as a "search" command


(most people wish it was named "search"). It is used to
search for text strings within one or more files.
grep 'fred' /etc/passwd
This command searches for all occurrences of the text string
13

'fred' within the "/etc/passwd" file. It will find and print (on
the screen) all of the lines in this file that contain the text
string 'fred', including lines that contain usernames like "fred"
- and also "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" in the name "fred" be in the first column of each record
(that's what the caret character tells grep). Using this moreadvanced search, a user named "alfred" would not be
matched, because the 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
Examples

The "mkdir" command is used to create new directories


(sub-directories).
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 the
directory "/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

14

This command creates a new directory named


/home/joe/customer/acme, and creates any intermediate
directories that are needed. If only /home/joe existed to begin
with, then the directory "customer" is created, and the
directory "acme" is created inside of customer.
Command
rmdir
Syntax
rmdir [options] directories
Description

Examples

The "rm" command is used to remove files and


directories. (Warning - be very careful when removing
files and directories!)
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 three
files specified. The -i option stands for inquire. You must
answer y (for yes) for each file you really want to delete. This
can be a safer way to delete files.
rm *.html
This command deletes all files in the current directory whose
filename ends with the characters ".html".
rm index*
This command deletes all files in the current directory whose
filename begins with the characters "index".
rm -r new-novel
This command deletes the directory named "new-novel". This
directory, and all of its' contents, are erased from the disk,
including any sub-directories and files.

Command
cd, chdir

15

Syntax
cd [name of directory you want to move to]
Description
Examples

"cd" stands for change directory. It is the primary


command for moving around the filesystem.
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 only
directory matching this wildcard pattern.
cd
Issuing the "cd" command without any arguments moves you
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 in
the middle of a project, and keep moving back-and-forth
between two directories.

Command
Syntax

kill
kill [options] IDs

Description
kill ends one or more process IDs. In order to do this you
must own the process or be designated a privileged user. To
find the process ID of a certain job use ps.
Examples
Command
Syntax

ps
ps [options]

16

Description

Examples

The "ps" command (process statistics) lets you check


the status of processes that are running on your Unix
system.
ps
The ps command by itself shows minimal information about
the processes you are running. Without any arguments, this
command will not show information about other processes
running on the system.
ps -f
The -f argument tells ps to supply full information about the
processes it displays. In this example, ps displays full
information about the processes you are running.
ps -e
The -e argument tells the ps command to show every process
running on the system.
ps -ef
The -e and -f arguments are normally combined like this to
show full information about every process running on the
system. This is probably the most often-used form of the ps
command.
ps -ef | more
Because the output normally scrolls off the screen, the output
of the ps -ef command is often piped into the more command.
The more command lets you view one screenful of
information at a time.
ps -fu fred
This command shows full information about the processes
currently being run by the user named fred (the -u option lets
you specify a username).

17

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:
Step2:
Step3:
Step4:

Start
read n
for i=1 to 10
print n*i
18

Step5:

Stop

Test Data:
Valid Data Set:

InValid Data Set:

n should not 0

Limiting Data Set:

n should be -300 to +300

Result
1) Enter the number 4
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
4*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:
Step2:

Start
read dir1
19

Step3:

if (dir1==dir name)
Print directory existes
Else
Print directory not exists
if step 3 is true then
Read file1
If file1 is exists
Copy the file1 into file2 and print The file copied to dir1 directory
Else File is not exists
Stop

Step4:
Step5:

Step6:
Test Data:

Valid Data Set:

Input should be a Directory name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result
1) Enter Directory Name :

Guru
Directory does not exist.

2) Enter Directory Name:

cse
Directory exist
Enter file name to be copied and type quit
File copied
Enter file name to be copied and type quit
File copied
Enter file name to be copied and type quit

Karuna
Rajani
quit

Viva-Voce Questions
1.
2.
3.
4.
5.
6.

Explain syntax of while loop?


How to check whether the given string is file or not?
Which command is used for copying a file?
Explain the syntax of command used for renaming the file?
Which command is used to list files in Directory
What vi stands for?

20

3) Name of the Experiment


AIM: Write a shell script that counts the number of lines and words present in a 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:
Step2:
Step3:

Start
read a file1
if file1 exists
21

Print no. of lines are.. l


Print no. of words are w
Print no. of characters are.. c
else
Print file1 is not exists
Stop

Step4:
Step5:
Test Data:

Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set

Not applicable

Result
1) Enter file name

Lines
:
Words :
Characters:
2) Enter file name
Lines
:
Words :
Characters:

Demo
This is demo
File to know
Number of words
Characters and line
4
13
65
engineer
Guru Nanak Engineering College
1
4
30

Viva-Voce Questions
1.
2.
3.
4.
5.
6.

Which command is used for display file?


Which command is used to count the no. of lines?
Explain the syntax of wc?
What is shell?
Explain the syntax of if loop?
What is vi editor?

22

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:

Start
23

Step2:
Step3:

read dir1
if (dir1==dir name)
Print Directory exists
if step3 is true
Read file1
if(-r dir1/file1) then
Print read
else if (-w dir1/file1) then
Print write
else if(-x dir1/file1) then
Print Execute
else
Print file1 is not exists
Stop

Step4:
Step5:
Step6:
Step7:
Step8:
Step9:

Test Data:
Valid Data Set:

Input should be a directory name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result
Enter the directory name
Directory exists
-a
file
Read
Write
Execute
-b
file
Read
Write
Execute

guru

24

Enter the directory name


nanak
Directory does not exists

Viva-Voce Questions
1.
2.
3.
4.
5.
6.

How to know what permission the file or directory has?


Which command is used to list file in given directory along with permission?
What is the purpose of sort command?
Explain syntax of cmp command?
How to know how many users are currently log in?
What is pwd?

5) Name of the Experiment


AIM: Write a shell script (small calculator) that adds , subtracts, multiplies and divides
the given two integers.
There are division options: one returns the quotient and the other 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).
S/W & H/W Requirements:
S/W: Office-XP, Turbo C.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

25

ALGORITHM
Step1:
Start
Step2:
read a, b, option
Step3:
if (option==1) then
Result=a+b
Print result
Step4:
if (option==2) then
Result=a-b
Print result
Step5:
if(option==3) then
Result=a*b
Print result
Step6:
if(option==4) then
Result=a%b
Print result
Step7:
if(option==5)
Result=a/b
Print result
Else if
Print Invalid operation
Step8:
Stop
Test Data:
Valid Data Set:

InValid Data Set:

Limiting Data Set:

the second number should not be Zero

Result
Enter two numbers:
Enter the choice
The result is

4 5
3
20

Enter two numbers:


Enter the choice
The result is

8
5
4

Viva-Voce Questions

26

1.
2.
3.
4.
5.
6.

Explain the syntax of switch case statement?


Which command is used for linking a file?
What do you mean by linking a file?
Which command is used for displaying time?
Which command is used to search a pattern in given file?
Explain syntax of cat command?

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: Start
27

Step2: read m1[],m2[],a, b


Step3: for i=1 to a
for j=1 to b
print m1[i][j]
Step4: for i=1 to b
for j=1 to a
m2[i][j]=m1[i][j]
Step5: print m2[i][j]
Step6: Stop
Test Data:
Valid Data Set:

1 2
3 4

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result
Enter the matrix size 2 3
Enter the matrix
The resultant matrix is

1
4

2
5

1
2
3

4
5
6

3
6

Viva-Voce Questions
1.
2.
3.
4.
5.

What are the three modes of vi editor?


Which commands are used to perform copy & paste operations in vi editor?
What is kernel?
What are the various shell responsibilities?
What are the various shell commands?

28

7) Name of the Experiment


AIM: 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:
Step2:

Start
read fiel1, char ch, int sc
29

Step3:
Step4:

initiate sc to 0 i.e sc=0


if(file1==NULL) then
Print unable to open a file
else if
While end of file
ch=fgetc(file1)
if(ch== )
sc=sc+1
print no. of spaces are sc
Stop

Step5:
Step6:
Step7:
Step8:
Step9:
Test Data:

Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result
1)

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

Spaces are 11
Viva-Voce Questions
1.
2.
3.
4.
5.

What is the procedure to create & execute C program in Unix?


What is system calls?
Explain the syntax of open() & read() system calls?
What is the purpose of lseek system call?
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) cat
b) ls
c) mv
S/W & H/W Requirements:
S/W: Office-XP, Turbo C.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

30

ALGORITHM:
(cat system call)
Step1:
Step2:
Step3:
Step4:
Step5:

Step6:
Step7:

Start
read

int fd,i
char ch[1]
if(argc<2)
Print Usage:mycat filename
fd=open ( argv[1],O_RDONLY)
if(fd==-1)
Print argv[1] is not exists
Else
Print Contents of the file are argv[1]
while(read(fd,ch,1)>0)
Print (ch [0])
Stop

(ls system call)


Step1:
Step2:
Step3:
Step4:
Step5:

Step6:

start
create a structure dinfo
read dp
if (argc<2)
dp=opendir( .)
if(dp==NULL)
Print unable to open the directory
Else
While(dinfo=readdir(dp))!=NULL)
Print dinfo->d_name
Stop

(My system calls)


Step1: Start
Step2: read a file *fp
Step3: if(argc<3)
Print Usage:my mv oldfile newfile
Else
If(access(argv[1],F_OK==-1)
Print file is not found
Step4: if(access(argv[2],F_OK==0)
Print File is already exists
Step5: rename(argv[1],argv[2])
31

Step6: print File moved or renamed successfully


Step7: Stop
Test Data:
Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result:
Implementing cat command
1) $ cc cat.c
$ ./a.out one
Contents of the file one is: Welcome to Unix Programming
Implementing ls command
$ cc ls.c
$ ./a.out kal
.
..
File 1
Kal2.sh
Implementing mv command
$ cc mv.c
$ ./a.out b c
File moved or renamed successfully

Viva-Voce Questions:
1.
2.
3.
4.
5.

Explain opendir() system call?


What are the various options that can be used with ls command?
Explain different uses of cat command?
What is the purpose of mv command?
What are the various elements of different structure?

32

9) Name of the Experiment:


AIM: Write a program that takes one or more file/directory names as command line input
and reports the following information on file:
c) File type.
d) Number of links.
e) Time of last access.
f) Read, Write and Execute permissions.
S/W & H/W Requirements:
S/W: Office-XP, Turbo C.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk
ALGORITHM
33

Step1:
Step2:

Start
read a FILE *stream
int buffer_character
stream= fopen(test,r)
if(stream==(FILE *))0)
Print (stderr,Error opening file(printed to standard error))
while ((buffer_character=getc(stream))!=EOF)
write the character to standard out and check for errors
if((putc(buffer_character,stdout))==EOF)
Print (stderr,Error writing to standard out.(printed to standard error))
if(fclose(stream))==EOF)
Print(stderr,Error closing stream.(printed to standard error))
stop

Step3:
Step4:
Step5:
Step6:
Step7:
Step8:
Step9:
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.c
Size 320
Type and permission : 10064
No.of links : 1
Access time . Apr 20 10:45:35

Viva-Voce Questions:
1.
2.
3.
4.
5.
6.

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


How to know the inode has no. of a particular file?
How we can access the inode table?
Explain the syntax of stat() & fstat() system calls?
What is the difference between stat() & fstat()?
What are the various elements of stat structure?

34

10) Name of the Experiment:


AIM: C program that illustrates how to execute two commands concurrently with a
command pipe
S/W & H/W Requirements:
S/W: Office-XP, Turbo C.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk
ALGORITHM

35

Step1:
Step2:
Step3:
Step4:
Step5:
Step6:

Step7:
Step8:
Step9:
Step10:

Start
read int i,pid
static char path[]=/u/test2
fork a child process
pid=fork()
if(pid==0)
chdir(path)
for i=0 to 30000
sub2()
i++ /*30000 calls to sub2 in child profile*/
else /*parent process.leave gmon.out in current directory*/
for i=0 to 1000
sub1(pid)
i++ /*1000 calls to sub1 in parent profile*/
read int sub1(pid) /*silly little function called by parent 1000 times
int pid,i
print (Im the parent ,child pid )
print(Im the child)
stop

Test Data:
Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result:
sh-2.00$ fork
Process 19643 about to fork a child.
PID TT S
TIME COMMAND
19632 p1 S
0:00.36 -bash (bash)
19638 p1 S + 0:00.07 script showem
19640 p1 S + 0:00.03 script showem
19641 p2 S
0:00.15 sh -is
19643 p2 S + 0:00.04 fork
19644 p2 S + 0:00.01 fork
19645 p2 S + 0:00.04 sh -c ps
19646 p2 R + 0:00.04 sh -c ps
19648 p2 R + 0:00.00 sh -c ps
PID TT S
TIME COMMAND

36

bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
19632 p1 S
0:00.36 -bash (bash)
19638 p1 S + 0:00.07 script showem
19640 p1 R + 0:00.03 script showem
19641 p2 S
0:00.15 sh -is
19643 p2 S + 0:00.04 fork
19644 p2 S + 0:00.01 fork
19645 p2 R + 0:00.04 sh -c ps
19646 p2 S + 0:00.04 sh -c ps
Created child process 19644.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
bbbbbbbb
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
sh-2.00$ exit
exit

37

Viva-Voce Questions;
1.
2.
3.
4.
5.

What is the pipeline? Explain with Example?


$who | wc l what will be the output of this command?
Pipeline is example of which redirection?
What is input & output of redirection?
What is the difference between the file and kernel?

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

38

Step1:
Step2:
Step3:
Step4:
Step5:

Start
read pid_t pid
pid=fork()
switch(pid)
if case = -1
Print Fork called
Else if case= 0
Print It is child process
Step6: else
Print It is parent process : CHILD PID is pid
Step7: 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.c
It is a child process
It is parent process : child pid is : 16281

Viva Voce Questions:


1.
2.
3.
4.
5.
6.

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

39

12) Name of the Experiment


AIM: Write a C Program that displays the real time of a day every 60 seconds
S/W & H/W Requirements:
S/W: Office-XP, Turbo C.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk
Step1:
Step2:

Start
create a structure of time t
Read int h,m,s,s1
40

Step3:
Step4:
Step5:

read time t
s1=t.ti_sec;
while(!kbhit())
h=t.ti_hour
m=t.ti_min
s=t.ti_sec
if(s1==s)
print( h,m,s)
Stop

Step6:
Step7:
Test Data:

Valid Data Set:


InValid Data Set:
Limiting Data Set:
Result
9:57:19
Viva-Voce Questions
1.
2.
3.
4.
5.

Explain gettime() function with example?


For what kbhit() function is used?
What are the elements of time structure?
What is the function of delay option?
What is the use of fcntl.h?

13 ) Name of the Experiment


AIM: Write a C Program that illustrates file locking using semaphores
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: Start
Step2: read int semidkey_t key
Step3: create a union semun
41

Step4: 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=1
Step7: 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.c
It is a child process
It is parent process : child pid is : 16281
Viva-Voce Questions:
1.
2.
3.
4.
5.

What is semaphore?
What are the two types of locking ?Explain difference?
What is file locking & record locking?
Which function is used for file locking explain with syntax?
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.
H/W: Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk
ALGORITHM
Step1: Start
Step2: create struct sembuf sop
42

int full ,empty,mutex


Step3: struct msg
read long mtype
char 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=full
down(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 I
read Pmsg.s
Pmsg.mtype=5
Step9: enter-item(int I)
int mqid
mqid=msgget((key-t)25,ipc-CREAT:0644)
msgnd(mqid,&pmsg,sizeof(pmsg.s)0)
print item written
Step10:down(int semid)
sop.sem-num=0
sop.sem-op=-1
sop.sem-flg=0
semop(semid,&sop,1)
Step11:up(int semid)
sop.em-num=0
sop.op=-1
sop.flag=0
semop(semid,&sop,1)
Step12:remove-item(int I)
int mqid
43

mqid=msgget((key-t)25,IPC-CREATE:0644)
msgrcv(mqid,&cmsg,sizeof(cmsg.s),5,0)
print item read from queue
Step13:Consume-item(int I)
Print item value is I,cmsg.s
Step14:/*main program*/
read pid,mqid
Step15: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() function
Else
Execute 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

Result:

44

Viva-Voce Questions:
1.
2.
3.
4.
5.

What is the two types of semaphores?


What is semget,semop,semctl functions?
What is producer,consumer problem?
How IPC is performed using pipe?
How pipe is created ?Expalin with example?

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: Start
Step2: read FILE *fp1, *fp2, *fp3, *fp4, *fopen()
45

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.5
Step7: srand48(1)
Step8: i=0i
Step9: i+=0.01)
Step10:y2 = (float) drand48()
Step11:if (i == 0.0)
y3 = 0.0
else
y3 = 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 */
flush(fp1)
flush(fp2)
flush(fp3)
flush(fp4)
Step14: /* plot graph */
PlotOne()
usleep(250)
void quit()
Step15: print caught: Shutting down pipes
Step16: StopPlot()
Step17: print closing data files
fclose(fp1)
fclose(fp2)
fclose(fp3)
fclose(fp4)
Step18: print deleting data files
Step19: RemoveDat()
Step20: Stop

46

Test Data:
Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result:
Enter files:
AB C D
Caught :Shutting down pipes
Closing data files

Viva-Voce Questions
1.
2.
3.
4.
5.

What is the purpose of interprocess communication?


What are the various IPC mechanisms?
How IPC is performed using shared memory?
What are the avripus shared memory system call?
What is shared memory?

16) Name of the Experiment:


AIM: Write a C program tha illustrates the following.
g) Creating a message queue.
h) Writing to a message queue.
i) reading from a 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
47

Step1: Start
Step2: /* Declare the message structure.*/
typedef struct msgbuf
long mtype
char mtext[MSGSZ]
message_buf
Step3: read int msqid
int msgflg = IPC_CREAT | 0666
key_t key
message_buf sbuf
size_t buf_length
Step4:

/* Get the message queue id for the


* "name" 1234, which was created by
* the server.
*/
key = 1234

Step5:
Step6:

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


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

48

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result:
Enter some text:
Enter some text:
Enter some text:
You Wrote:
You Wrote:
You Wrote:

Hello
How r u
Today
Hello
How r u
Today

Viva-Voce Questions:
1.
2.
3.
4.
5.

How IPC is performed using message queue?


What are various message system calls?
What are various message operations?
Explain message passing with example?
What is signal? What are various signal functions?

LAB OBJECTIVE
The language Processors comprises assemblers, compilers and interpreters. It deals with
the recognition the translation, and the execution of formal languages It is closely related
to compiler construction.

Students will gain the knowledge of


49

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 on
interpretive definitions)
Implementation of programming concepts, control structures
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 by designing 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 C crossed with
Pascal. The syntax of the language is defined by the following BNF grammar
<program> ::= <block>
<block> ::= { <variabledefinition> <slist> }
50

| {<slist>}
<variabledefinition> ::= int <vardeflist> ;
<vardeflist> ::= <vardec> I <vardec> , <vardetlist> <vardec> ::= <identifier> I
<identifier> [ <constant> ] <slist> ::= <statement> I <statement> ; <slist>
<statement> ::= <assignment> I <ifstatement> I <whilestatement> I <block> I
<printstatement> I <empty>
<assignment> ::= <identifier> = <expression>
I <identifier> [ <expression> ] = <expression> <ifstatement> ::= if <bexpression> then
<slist> else <slist> endif
I if <bexpression> then <slist> endif <whilestatement> ::= while <bexpression> do
<slist> enddo <printstatement> ::= print ( <expression> )
<expression> ::= <expression> <addingop> <term> 1 <term> 1 <addingop> <term>
<bexpression> ::= <expression> <relop> <expression>
<relop> ::= < I <= I == I >= I > I !=
<addingop> ::= + 1<term> ::= <term> <multop> <factor> I <factor> <multop> ::= ' 1/
<factor> ::= <constant> I <identifier> 1 <identifier> [ <expression>]
I ( <expression> )
<constant> ::= <digit> 1 <digit> <constant> <identifier> ::= <identifier> <Ietterordigit> I
<letter> <lelterordigit> ::= <letter> I <digit>
<letter> ::= alblcldlelflglhlililklllmlnlolplqlrlsltlulvlwlxlYlz
<digit> ::= 0|1|2|3|4|5|6|7|8|9|
<empty> has the obvious meaning
Comments (zero or more characters enclosed between the standard C/Java-style comment
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 the scoping 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 then
print(t2);
else {
int t3;
t3=99;
t2=-25;
51

print{-t1+t2*t3); /* this is a comment on 2 lines */


) endif)
1.
Design a Lexical analyzer for the above language. The lexical analyzer should
ignore redundant spaces, tabs and newlines. It should also ignore comments. Although
the syntax specification states that identifiers can be arbitrarily long, you may restrict the
length to some reasonable value.
2.
Implement the lexical analyzer using flex, flex or lex or other lexical analyzer
generating tools.
3.
Design Predictive parser for the given language
4.
Design LALR bottom up parser for the above language.
5.
Convert the BNF rules into Yacc form and write code to generate abstract syntax
tree.
6.
Write program to generate machine code from the abstract syntax tree generated
by the parser. TI following instruction set may be considered as target code.
The following is a simple register-based machine, supporting a total of 17 instructions. It
has the distinct internal storage areas. The first is the set of 8 registers, used by the
individual instruction as detailed below, the second is an area used for the storage of
variables and the third is an area for the storage of program. The instructions can be
preceded by a label. This consists of an int, in the range 1 to 9999 and the label is
followed by a colon to separate it from the rest of II instruction. The numerical label can
be used as the argument to a jump instruction, as detailed bel In the description of the
individual instructions below, instruction argument types are specified follows:
R
specifies a register in the form RO, R1, R2, R3, R4, R5, R6 or R7 (or rO, r1, etc.).
L
specifies a numerical label (in the range 1 to 9999).
v
specifies a ''variable location" (a variable number, or a variable location pointed to by a
register below).
A
specifies a constant value, a variable location, a register or a variable location pointed to
by a regi (an indirect address). Constant values are specified as an integer value,
optionally preceded~, minus sign, preceded by a # symbol. An indirect address is
specified by an @ followed by a regi So, for example, an A-type argument could have the
form 4 (variable number 4), #4 (the constant 4), r4 (register 4) or @r4 (the contents of
register 4 identifies the variable location to be access,
The instruction set is defined as follows:
LOAD A,R
loads the integer value specified by A into register R.
STORE R,V
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
52

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 L
Causes 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 than or equal
to zero.
JGT R,L
jumps to the instruction with the label L if the value in register R is greater than zero . . 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 than zero.
NOP
is an instruction with no effect. It can be tagged by a label.
STOP
stops execution of the machine. All programs should terminate by executing a STOP
instruction.

Syllabus Programs

S.No Name of the Program

Page
No

53

54-56
1

Design a Lexical analyzer. The lexical analyzer should ignore redundant s


tabs and new lines. It should also ignore comments. Although the syntax
specification s that identifiers can be arbitrarily long, you may restrict the
length to some reasonable Value.

Implement the lexical analyzer using JLex,flex or lex other lexical


analyzer generating tools.

Design Predictive Parser for the given language

57-58

59-60
61-62
4

Design LALR bottom up parser for the above language

Convert the BNF rules into YACC form and write code to generate
abstract syntax tree

63-64

65-66
6

Write program to generate machine code from the abstract syntax tree
generated by the Parser .The following instruction set may considered as
target code.

1) Name of the Experiment:


AIM: Design a Lexical analyzer. The lexical analyzer should ignore redundant s tabs and
new lines. It should also ignore comments. Although the syntax specification s that
identifiers can be arbitrarily long, you may restrict the length to some reasonable Value.
S/W & H/W Requirements:
S/W:

Yet Another Compiler to Compiler (YACC) Compiler, Office XP,

54

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 symbol table. 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 symbol table and
the corresponding address is returned.
Step1:
Step2:

Step3:

Step4:

Start
function scan
lexbuf[50] of char
tokenvalue[10]
begin
store scanned char in c
if c blank or tab,then
do nothing
else if c is \n,then
line_number :=line_number=1
else if c is a digit
token value:=value of the digit and successive digits
return tokentype
p:=lookup(lexbuf)
if p:=NULL, then
p:=insert(lexbuf,id)
token value:=lexbuf
return(attribute from symboltable)
else
tokenvalue:=NULL
return(NULL) end
Stop

Test Data:
Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

55

Result
INPUT file xx.txt
{
int t1,t2
t1=2
t2=t1*3/2;
if t2>5 then
print(t2);
else
{
int t3;
t3=99;
t2=-25
print(-t1+t2+t3);
}
End if
OUTPUT
SOB
int
ID
SEPE
ID
ENDST
ID
ASSIGN
ENDST
ID
ASSIGN
ID
MULOP
DIVOP
ENDST
If
ID
GT
NUM
Then
print
OPENPRA
ID
CLOSEPRA
ENDST

else
SOB
int
ID
ENDST
ID
ASSIGN
NUM
ID
ASSIGN
SUBOP
NUM
ENDST
OPENPRA
SUBOP
ID
ADDOP
ID
MULOP
ID
CLOSEPRA
ENDST
EOB
endif

56

Viva-Voce Questions
1.
2.
3.
4.
5.

What is lexical analyzer?


Which compiler is used for lexical analyzer?
What is YACC?
What is the output of Lexical analyzer?
What is LEX source Program?

2) Name of the Experiment:


AIM: Implement the lexical analyzer using JLex, flex or lex other lexical analyzer
generating tools.
S/W & H/W Requirements:
S/W:

Yet Another Compiler to Compiler (YACC) Compiler, Office XP,

57

H/W:

Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

ALGORITHM:
Step1:
Step2:

Start
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]
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)}
<{print(logoical operators)}
<={print(logoical operators)}
>={print(logoical operators)}
= {printf(\n \n)}
!{printf(\n \n)}
+ {printf(arithmetic operator)}
- {printf (arithmetic)
* {printf(arithmetic)}
% {printf(arithmetic)}
% % {printf(arithmetic)}
Step3: Write the auxillary procedure in main() function
Step4: end
Step5: Stop

Test Data:
Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result
58

Viva-Voce Questions
1. What is Parsing?
2. Construct the parsing table for the given?
S1 iC+SS1|a
S1 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

59

ALGORITHM
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:
Step7:
Step8:
Step9:
Step10:

Start
declare w[10] as char and Z as an array
enter the string with $ at the end
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 then increment and check for
(D(w[z]))
if step 4 is satisfied then the string is accepted
Else string is not
give for the grammer A-> bc/ab in the loop A(int k)
Describe the grammer b->c/d in the loop B (int k)
Similarly describe the grammer D->d/abcd
if steps7,8,9 are satisfied accordingly string is accepted
Else string is not accepted
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
{
int a, ba[10];
a=a*a;
b=a*b;
if a<b
print (a);
else
print(b);
}

aa.txt

OUTPUT:
Successful parsing

60

Viva-Voce Questions

1.
2.
3.
4.
5.

What is Predictive parser?


How many types of analysis can we do using Parser?
What is Recursive Decent Parser?
How many types of Parsers are there?
What is LR Parser?

4) Name of the Experiment:


AIM:

Design LALR bottom up parser for the above 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


61

ALGORITHM
Step1:
Step2:
Step3:
Step4:
Step5:
Step6:
Step7:
Step8:
Step9:

Step10:

Start
Initially the parser has s0 on the stack where s0 is the initial state and w$
is in buffer
Set ip point to the first symbol of w$
repeat forever, begin
Let S be the state on top of the stack and a symbol pointed to by ip
If action [S, a] =shift S then begin
Push S1 on to the top of the stack
Advance ip to next input symbol
Else if action [S, a], reduce A->B then begin
Pop 2* |B| symbols of the stack
Let S1 be the state now on the top of the stack
Output the production A->B
End
else if action [S, a]=accepted, then return
Else
Error()
End
Stop

Test Data:
Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result
[
[
[
[

] $ lex parser.l
] $ Yacc -d parser.y
] $ cc lex.yy.c y.tab.c -ll -ld
] $ ./a.out

2+3
5.000

62

Viva-Voce Questions
1.
2.
3.
4.
5.

What is LALR parsing?


What is Shift reduced parser?
What is the operations of Parser?
What is the use of parsing table?
What is bottom up parsing?

5) Name of the Experiment:


AIM: Convert the BNF rules into YACC form and write code to generate abstract
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


63

ALGORITHM
Step1:
Start
Step2:
declare the declarations as a header file
{include<ctype.h>}
Step3:
token digit
Step4:
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 routines
Step6:
Stop
Test Data:
Valid Data Set:

Input should be a file name

InValid Data Set:

Not applicable

Limiting Data Set:

Not applicable

Result
[
[
[
[

POS
0
1
2
3
4
5
6
7

]
]
]
]

Operator
<
==
+
=
Goto
<
==
+

$ lex int.l
$ Yacc -d int y
$ cc lex.yy.c y.tab.c -ll -ly
$ ./a.out test.c

Arg1
a
to
a
t1

Arg2
b
FALSE5
b

a
t2
a

b
FALSE10
b

Result
to
+1
a
5
t2
+3
64

8
9
10
11
12
13
14
15
16

=
GOTO
<=
==
=
GOTO
+
=

t3
a
t4
a
t5

b
FALSE+=5
b

a
t6

a
5
t4
+5
c
17
t6
c

Viva-Voce Questions
1.
2.
3.
4.
5.

What is Abstract Syntax tree?


What are BNF Rules?
What is DAG representation?
How LALR(1) states are generates?
In which condition the user has to supply more information to YACC?

6) Name of the Experiment:


AIM: Write program to generate machine code from the abstract syntax tree generated
by the Parser .The following instruction set may considered as target code.
S/W & H/W Requirements:
S/W:

Yet Another Compiler to Compiler (YACC) Compiler, Office XP,

65

H/W:

Pentium IV Processor, 256 MB RAM, 40 GB Hard Disk

ALGORITHM
Step1:
Start
Step2:
for every three address statement of the form x=y op z
Step3:
begin
Step4:
Call getreg() to obtain the location L which the computation y op z should
be performed
Step5:
Obtain the current location of the operand y by consulting its address
descriptor ,and if the values of Y are currently both in the memory location
as well as in the register, then prefer the register.If the value of y is not
currently available in 1,then generate an instruction MOV y,l
Step6:
Generate the instruction OP Z,l and update the address descriptor of X to
indicate that X is now available in l and in register then update t\ its
descriptor to indicate that it will contain the run time value of x
Step7:
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 no longer contain y and / or z.
Step8:
store all results
Step9:
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
a
a
a

2
1
2
3

2
3
4
66

Output file target.txt


STORE
STORE
STORE
STORE

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

LOAD a , R0
LOAD b , R1
ADD R1 , R0
SUB R0 , c

Viva-Voce Questions
1.
2.
3.
4.
5.

What is target code?


What is machine code?
What is Cross compiler?
Give the example for cross compiler?
What is the difference between syntax & Semantics?

References:
BOOKS:
Unix the ultimate Guide,
Unix networking programming,
Advanced Programming in Unix environment,

Sumitabha das,TMH
W.R Stevens Pearson/PHI
W.R Stevens Pearson/PHI

Principles of Compiler Design,


Modem Compiler Implementation in C

LMAN Narosa
Andrew N. Appel,Cambridge
University Press
John R.Levine,Tony Mason,Doug

Lex&yacc

67

Brown,Orelly

WEBSITES:
www.unix.com
www.compilerdesign.com
www.lexicalanalyzer.com
www.w3school.com

68

You might also like