0% found this document useful (0 votes)
143 views

Unix & CD Lab Manual - III B.tech.-27!01!2075

This document provides a lab syllabus for a Unix Programming & Compiler Design course. It outlines 12 topics that students will cover, including: [1] practicing Unix commands like file handling, security permissions, and text processing; [2] writing shell scripts; [3] using awk scripting; [4] writing C programs that perform tasks like copying files and creating processes; [5] implementing parsing techniques; and [6] using lex and yacc. For each topic, example programs are listed that students will complete to demonstrate their proficiency with the various Unix and programming concepts covered in the course.

Uploaded by

Hacker Pinky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views

Unix & CD Lab Manual - III B.tech.-27!01!2075

This document provides a lab syllabus for a Unix Programming & Compiler Design course. It outlines 12 topics that students will cover, including: [1] practicing Unix commands like file handling, security permissions, and text processing; [2] writing shell scripts; [3] using awk scripting; [4] writing C programs that perform tasks like copying files and creating processes; [5] implementing parsing techniques; and [6] using lex and yacc. For each topic, example programs are listed that students will complete to demonstrate their proficiency with the various Unix and programming concepts covered in the course.

Uploaded by

Hacker Pinky
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 70

Department of Computer Science and Engineering

UNIX Programming & Compiler Design Lab

III Year – I Sem B.Tech

2016-2017

Prepared by : Mrs.Dr. G.Karuna, B.Rupa, R.N.Ashlin Deepa and G.Lavanya


Gokaraju Rangaraju Institute of Engineering& Technology
Bachupally, Hyderabad-500 072

Unix Programming & Compiler Design lab Page 1


List of Programs (Lab Syllabus)

S.No. Contents
a) Practice the following commands in UNIX environment
(i) File Handling Utilities (ii) Disk Utilities
b) Practice the given commands in UNIX environment
T1.
(i) Security by File Permissions (iii) Process Utilities
c) Demonstrate all Text Processing Utilities in UNIX.
d) Practice Stream editor commands.

a) Write a shell script to print the sum of even numbers from given n
numbers.
b) Write a shell script that accepts a file name as argument and display
T2. specified number of lines from the beginning of file.
c) Write a shell script that takes an argument and checks if argument
supplied is a file or a directory and reports accordingly. If the
argument is a directory, display the contents of directory.

a) Write a shell script to demonstrate the creation of a menu to display


list of files, process status, users of a system, current date, present
working directory and exit from prompt (using case statement).

T3. b) Write an awk script to count the number of lines in a file that do
not contain vowels.
c) Write an awk script to find the number of characters, words and
lines in a file.

a) Write a C program that makes a copy of a file using standard I/O


and system calls.
b) Implement in C the following UNIX commands using System calls
A. cat B. ls

c) Write a program that takes one or more file/directory names as


command line input and reports the following information on the file.
T4. A. File type. B. Number of links.
C. Time of last access. D.Read, Write and Execute permissions.
d) Write a C program that demonstrates redirection of standard output
to a file.

Ex: ls> f1

T5. a) Write a C program to create a child process and allow the parent to

Unix Programming & Compiler Design lab Page 2


display “parent” and the child to display “child” with Process
ID’s on the screen.

b) Write a C program to create a Zombie process.

c) Write a C program that illustrates how an orphan is created.

d) Write a C program that illustrates suspending and resuming


processes using signals.

a) Write a C program that illustrates how to execute two commands


concurrently with a command pipe. Ex: - ls –l | sort
T6.
b) Write C programs that illustrate communication between two
unrelated processes using named pipe.

Design a lexical analyzer for tokenizing an expression and identify comment


T7.
lines in the program.

Implement top down parsing techniques.


T8.
a) Brute force technique b) RDP

Find the first set and follow of a given grammar.


T9.
Design shift-reduce parser for a given grammar
T10.

T11. Implement intermediate code generation and code generation for a given

expression.

a) LEX Program to count the number of lines, words and letters, capital
letters, small letters and digits in a file.
T12.
b) Function usage in LEX program.
c) Design a simple arithmetic calculator: USE LEX and YACC.
Case Study: Implement parsing techniques for a given grammar and show
DFA.

Task1:

Unix Programming & Compiler Design lab Page 3


a) Practice the following commands in UNIX environment

(i) File Handling Utilities


1) $cat:used to create files.
Syntax:$cat >filename
Example:$cat >csed
UNIX programming lab [ctrl+d]
OUTPUT:
$cat csed
UNIX programming lab

Options:
Syntax: $touch [options] filename

a)-c:$ is printed at the end of each line,this option should be used with ‘-’.
Syntax:$cat -c -v filename
Example:$cat -c -v test
OUTPUT:Hello GRIET$

b)-t:Each tab will display as ^I and each form will display ^.


Syntax:$cat -t filename
Example:$cat -t test
OUTPUT:Hello ^IGRIET

c)-n:D isplays line numbers in file.


Syntax:$cat -n filename
Example:$cat -n clg.txt
OUTPUT:1.Welcome to GRIET
2.My branch is CSE

2)$touch: To create more than one file at a time with zero bytes.
Syntax:$touch file1 file2 file3 …. filen
Example:$touch f1 f2 f3…fn

Options:
Syntax:$touch [options] filename

a)-a:changes only access time


Syntax:$touch -a filename
Example:$touch -a clg.txt
OUTPUT:Access:2016.09.24 23:58:21
Access:2016.09.24 00:08:23

b)-c: Does not create a file,if it does not exists

Unix Programming & Compiler Design lab Page 4


Syntax:$touch -c filename
Example:$touch -c t1.txt

c)-m: Changes only modification time.


Syntax:$touch -m filename
Example:$touch -m clg.txt

3)$cp:used for copying files.


Syntax:$cp [options] source_file destination-file
Example:$cp f1 f2
OUTPUT:
$cat f1
This is GRIET
$cat f2
This is GRIET
Options:
a)-f: Force copy by removing the destination file if needed.
Syntax: $cp -f source_file destination-file
Example:$cp -f f1 f2
OUTPUT:$cat f1
This is CSE
$cat f2
This is GRIET

b)-i: Ask the confirmation to overwrite.


Syntax: $cp -i source_file destination-file
Example:$cp -i f1 f2

c)-b:It creates backup files before overriding.


Syntax: $cp -b source_file destination-file
Example:$cp -b f1 f2

4)$mv: Used to move files and directories and rename file.


Syntax:$mv [options] source destination
Example:$mv f1 f2
OUTPUT: file renamed from f1 to f2

Options:
a)-f:Force move by overwriting destination file without prompt.
Syntax:$mv -f source destination
Example: $mv -f main.c main.txt

b)-i: interactive prompt before overwriting.

Unix Programming & Compiler Design lab Page 5


Syntax: $mv -i source destination
Example: $mv -i f1 f2

c)-u: Update / move when source is newer than destination .


Syntax:$mv -u source destination
Example: $mv -u f1 f2

5)$rm: Used to remove files or directories.


Syntax: $rm [options] filename
Example:$rm f1
OUTPUT:
f1 is deleted

Options:
a)-f: ignores non existing files, never prompt
Syntax: $rm -f filename
Example: $rm -f myfile.txt
OUTPUT:Removes file myfile.txt

b)-r: Removes directories and their content.


Syntax: $rm -r filename
Example: $rm -r mydirectory
OUTPUT:Removes directory mydirectory and all files in it.

c)-i: prompts before every removal.


Syntax: $rm -i filename
Example: $rm -i bak.c

6)$link: ($ln) : it creates links between files.


Syntax:$ln source_file destination_file
Example:$ln student1 student2

7)$unlink: it removes the link between the files.


Syntax:$unlink filename
Example: $unlink Student1

ii). DISK UTILITES:

1.$du:

It is used to estimate the file space usage.

Syntax: $du <file name>

Unix Programming & Compiler Design lab Page 6


Example: $du rf.c

Output: 4 rf.c

2. $df:

It reports the amount of free space available for each file system separately i.e;
estimate the free space.

Syntax: $df <file name>

Example: $df rf.c

Output: File system 1k-blocks used avail use%

/dev/sda1 305478904 3979128 285939312 2%

3. $mount:

It is used to attach all file systems available in same device to the tree structure.

Syntax: $mount[option]<device name or path name><directory/path name>

Example: $mount \dev\edROM \mnt\cd

Options:

-t: specifies type of file system.

Ex:$mount –t ext2 /dev/hda3/oracle

Output:Linux.

-a: mounts all file system that are listed in a configuration file

4. $umount/$unmount:

This command is used for detaching a file system from unix tree structure.

Unmounting is not possible if you have a file already opened.

Syntax: $unmount[option]<directory/path>

Example: $umnount \mnt\cd

Options:

-r: try to remount read only mode

Example:$umount –r /usr/local

Output: only readonly mode /usr/local directory

Unix Programming & Compiler Design lab Page 7


-a: all the file system are located on /etc/mtab.

b) Practice the given commands in unix environment


i).SECURITY BY FILE PERMISSIONS:

1.$chmod:

It is used to change the file permissions.

Syntax: $chmod<permission><file name>

Example: suppose the file having permissions

ls –l student.list

rwx-x-wx csedept csedept 104 jul 15 11:09 student1.list

(all examples are related to this file)

Example: $chmod ugo+r student1.list - remove lock to read

Output: rwx-rx-rwx csedept csedept 104 jul 15 11:09 student1.list

Example: $chmod ugo-rwx student1.list – add locks

$ls –l student1.list

Output: --------------1 csedept csedept 104 jul 15 11:09 student1.list

Example:$chmod 777 student1.list .

Output: rwx-rwx-rwx csedept csedept 104 jul 15 11:09 student1.list

2.$umask:

The default permissions may be altered by super user.The default permissions are
transformed by subtracting the user mask from it to remove one or more permissions.

Syntax: $umask [umask value]

Example: $umask 022 (default shell /settings/acess permissions)

Output: This becomes 644 (666-022) for ordinary file and 755(777-022) for
directories.

It will have permissions(file) - ->rw-r—r—

ii).PROCESS UTILITES:

1.$ps(Process Status):

Unix Programming & Compiler Design lab Page 8


This command is used to display the attributes of a process.

Syntax: $ps

Example: $ps

Output: PID TTY TIME CMD

644 01 10:30:00 bash

643 02 10:31:00 ps

Options:

-f: detailed listing which shows parent of every process,use(-f)->(full) option.

Example: $ps –f

Output:

UID PID PPID C STIME TTY TIME CMD

Sumid 291 1 0 10:24:36 console 0:00 –bash

-u:it displays processes of a user.

Example: $ps –u sumit

Output: PID TTY TIME CMD

378 ? 00:05 xsun

403 ? 00:00 xsession

-a: displaying all user processes.

Example: $ps –a

Output : PID TTY TIME CMD

662 pts/01 00:00:00 ksh

705 pts/02 00:00:00 sh

2.$kill:

This command is used to kill the process i.e; stop or terminate a process.(by
administrator)Syntax: $kill <pid>

Example: $kill 644

Output: The process gets terminated.

Unix Programming & Compiler Design lab Page 9


C) Demonstrate all Text Processing Utilities Using UNIX commands:

1.$grep: Used to search,select and Print Specified records or lines from an input files.
Syntax:$grep [options] pattern [filename1][filename2]………..

Eg:$cat >st.list

Sid name Dob

1 XXX 123

2 XYZ 234

3 ZZZ 345

$grep ZZZ st.list

OUTPUT: 3 ZZZ 345

Options:

i)-i(ignoring case): This ignores Case for pattern matching.

Eg:$grep -i Zzz st.list

Output: 3 ZZZ 345

ii)-v(deleting lines):This selects all lines except those containing the pattern.

Eg:$grep -v XXX st.list

Output:2 XYZ 234

3 ZZZ 345

iii)-c:it counts lines containing pattern.

Eg: $grep –c XXX st.list

Output:1

2.$tee: It handles a character stream by duplicating its input and it saves one copy in a file
and when others copy the output.

Syntax: $tee [options] <filename>

Ex:$who/tee user.txt

Cselab tty 2016-07-18 12:38(:0)

Cselab pts/2 2016-07-18 12:38(:0)

Unix Programming & Compiler Design lab Page 10


$cat user.txt

Cselab tty 2016-07-18 12:38(:0)

Cselab pts/2 2016-07-18 12:38(:0)

Options:

i)-a: append to the given files do not overwrite.

Syntax: $tee –a <filename>

Eg:$tee –a foo.txt

Output: batch

$cat foo.txt

foo

batch

ii)-i:ignores the interrupt

Syntax:$tee –I <filename>

Eg: $tee –i foo.txt

3. $cmp:It makes a comparison of each byte of two files and terminates the moment it
encounters difference.

Syntax:$cmp group1 group2

Eg: $cat >same

Good Morning

$cat >same1

Good Night

Welcome

to USP&CD lab

$cmp same1 same

Output: same same1 differ:byte1,line1

Options:

i)-i:skip first skip bytes of both files

Unix Programming & Compiler Design lab Page 11


Syntax:$cmp –i 5 same same1

Output: same same1 differ:byte5,line5

ii)-l:Output byte numbers and differing byte values

Eg:$cmp –l –i 5:2 same same1

Output: 1 155 40

2 145 156

3 40 141

iii)-n:compare atmost limit bytes

Eg: $cmp –l –n 10 –i 5:2 same same1

Output: 1 155 40

2 145 156

3 40 141

4. $comm:It compares the files line by line and displays the common and differing lines.
Syntax:$comm <file1><file2>

Eg: $cat >cities1 $cat >cities2

Agra Banglore

Banglore Chennai

Chennai Delhi

Mysore Mysore

Output:$comm cities1 cities2

Agra

Banglore

Chennai

Delhi

Mysore

Unix Programming & Compiler Design lab Page 12


Options:

i)-1:suppresses the first column

Eg: $comm -1 cities1 cities2

Output:

Banglore

Chennai

Delhi

Mysore

i)-2:suppresses the second column

Eg: $comm -2 cities1 cities2

Output:

Agra

Banglore

Chennai

Mysore

i)-3:suppresses the third column

Eg: $comm -3 cities1 cities2

Output:

Agra

Unix Programming & Compiler Design lab Page 13


Delhi

5. $diff:It analyzes two files and prints the different lines.


Syntax:$diff [opt] <file1><file2>

Eg:$cat >f1 $cat >f2

Rama 112 Rama 112

Sita 113 Sita 113

Laxman 114

$diff f1 f2

Output: Laxman 114

Options:

i)-b: Ignores blank spaces.

Syntax: $diff –b file1 file2

Eg: $diff –b file1 f1.txt

|c| |c| indicates by changing line no. 1 of first line

<good Morning with line no.1 of second file then file can be

_______________ matched.

>good night

ii)-i:It checks for mistakes.

Syntax:$diff –i file1 file2

Eg:$diff –i f.txt f1.txt

1 , 3c1 , 3

<Unix

<command

<if(a==b)

>

Unix Programming & Compiler Design lab Page 14


>

>

6. $head: It is used to describe the first few lines of a file.


Syntax:$head [options] <filename>

Eg: $head file1

Output: The first ten lines of the file are displayed.

Options:

i)-n:Specifying the number of lines.

Syntax:$head –n <filename>

Eg:$head –n 3 file3

Output: The first 3 lines of the file are displayed.

ii)-u: Prints first 10 lines.

Syntax:$head –u <filename>

Eg: $head –u file3

Output: ==>file3 <==

Jan

Feb

Mar

……

Oct

7.$tail:It is used to view last few lines of a file.


Syntax:$tail [options] <filename>

Eg: $tail f1.txt

Output: Apple

Unix Programming & Compiler Design lab Page 15


Grape

Options:

i)-c:Prints the characters from last .

Syntax:$tail -c <filename>

Eg:$tail -c -5 f1.txt

Output: Apple

ii)-v:Prints the header of given file.

Syntax:$tail –v <filename>

Eg:$tail –v f1.txt

Output: ==> f1.txt<==

Apple

Grape

8.$sort: Used to sort the information in the file.


Syntax:$sort [options] <filename>

$cat >sort1

computer

Computer

COMPUTER

123456

@#$%^

$sort sort1

Output:@#$%^

123456

Computer

Computer

COMPUTER

Options:

Unix Programming & Compiler Design lab Page 16


i)-d:Used to sort according to dictionary order.

Syntax:$sort [options] <filename>

Eg:$cat >sort2

f*()

123

abc

)(*f

$sort –d sort2

Output: )(*f

f*()

123

Abc

ii)-m:Used for merging files.

Eg:$sort –m sort2

Output: &*()

123

abc

) (*&

ii)-n:It is used to sort numeric files.

Eg:$ cat >abc

12

33

45

Output:$sort –n abc

12

Unix Programming & Compiler Design lab Page 17


33

45

9.$tr:It translates or deletes character from standard input and writing into standard output
device.

Syntax:$tr [option][exp1][exp2][standard i/p]

Example:$tr a x

akshitha

Output:xkshithx

10.$cut:This command splits vertically.By using this command , required fields or columns
can be extracted from a file.

Syntax:$cut [option]<file name>

Example:$cat >s1.list

USN NAMESEMESTER BRANCH DOB

111? aaa ? 5?cse?25-aug-96

222?bbb?6?cse?28-sep-97

333?ccc?7?cse?14-feb-97

Options:

i)-c:$cut –c 3 -s1.list

Output:N NAMESEMESTER BRANCH DOB

1? aaa ? 5?cse?25-aug-96

2?bbb?6?cse?28-sep-97

3?ccc?7?cse?14-feb-97

d) Practice stream editor commands:


S.No Commands Description
1 i,a,c Inserting,appending,changing
2 1,4d 1 to 4 lines will be deleted
3 s/s1/s2 S:-substitution of text replaces first occurrence of string or
regular expression , s1 with string s2
4 3,$p 3 to end of lines will be printed
5 Q Quit(read the first line and quit)
6 $!p All line except last line will be printed

Unix Programming & Compiler Design lab Page 18


7 s/s1/s2/g All the occurrence of s1in the file will be replaced i.e; s1 will
replace with s2 string
8 s/s1/s2/g/2 Replace a particular line for ex:2nd line s1 will be replaced with
s2
9 Inserting text $sed `1i\aaa bbb ccc `\bank.txt

Creating bank1.txt file

$cat >bank.txt

a/c no name balance date of opening type of a/c

101 akshi 50000 11/4/13 CURRENT

102 priya 70000 15/5/15 SAVINGS

103 sowmya 55000 12/2/15 CURRENT

104 hari 65000 13/6/11 SAVINGS

$sed ‘1,2p` bank1.txt

a/c no name balance date of opening type of a/c

a/c no name balance date of opening type of a/c

101 akshi 50000 11/4/13 CURRENT

102 priya 70000 15/5/15 SAVINGS

103 sowmya 55000 12/2/15 CURRENT

104 hari 65000 13/6/11 SAVINGS

$sed –n `1.2p` bank1.txt

a/c no name balance date of opening type of a/c

101 akshi 50000 11/4/13 CURRENT

$sed –n `$p` bank1.txt

104 hari 65000 13/6/11 SAVINGS

$sed –n `3,$p` bank1.txt

102 priya 70000 15/5/15 SAVINGS

103 sowmya 55000 12/2/15 CURRENT

Unix Programming & Compiler Design lab Page 19


104 hari 65000 13/6/11 SAVINGS

$sed –n `$!p` bank1.txt

a/c no name balance date of opening type of a/c

101 akshi 50000 11/4/13 CURRENT

102 priya 70000 15/5/15 SAVINGS

103 sowmya 55000 12/2/1 CURRENT

$sed –n –e `1,2p’ –c `3,4p` bank1.txt

a/c no name balance date of opening type of a/c

101 akshi 50000 11/4/13 CURRENT

102 priya 70000 15/5/15 SAVINGS

103 sowmya 55000 12/2/15 CURRENT

$sed –n `s/CURRENT/SAVINGS/p` bank1.txt

101 akshi 50000 11/4/13 SAVINGS

103 sowmya 55000 12/2/15 SAVINGS

Unix Programming & Compiler Design lab Page 20


Task2:
2(a). Write a shell script to print the sum of even numbers from given n numbers.
AIM: To write a shell script to print the sum of even numbers from given n numbers.
Script:
echo “enter a value”
read n
s=0
i=0
while [ $i –le $n ]
do
if [ `expr $i%2` -eq 0 ]
then
s= `expr $s + $i `
fi
i= `expr $i + 1`
done
echo “sum of n even numbers”
echo $s
OUTPUT:
enter a value
10
Sum of n even numbers
30

Unix Programming & Compiler Design lab Page 21


2(b). Write a shell script that accepts a file name, starting and ending line numbers as
arguments and displays all the lines between the given line numbers.

AIM: Shell script that accepts a file name, starting and ending line numbers as
arguments and displays all the lines between the given line numbers.

Script:
if [ $# -le 2 ]
then
echo "insufficient arguments"
fi
if [ $2 -gt $3 ]
then
echo "arguments are not proper"
fi
x=`expr $3 - $2 + 1`
cat $1 | head -$3 | tail -$x

OUTPUT:
$sh p1.sh test 2 4
hello
hai
griet

$ cat test
welcome
hello
hai
griet
karuna

Unix Programming & Compiler Design lab Page 22


2(c). Write a shell script that receives any number of file names as arguments checks if
every argument supplied is a file or a directory and reports accordingly. Whenever the
argument is a file, the number of lines on it is also reported

AIM: Shell script that receives any number of file names as arguments checks if every
argument supplied is a file or a directory

Script:

for x in $*
do
if [ -f $x ]
then
echo " $x is a file "
echo " no. of lines in the file $x are: "
wc -l $x
elif [ -d $x ]
then
echo " $x is a directory "
else
echo " enter valid filename or directory name "
fi
done

OUTPUT:

$cse$karuna$sh p4.sh
f1 is a file
no.of lines in the file f1 are : 4
f2 is a file
no.of lines in the file f2 are: 3
test is a file
no.of lines in the file test are: 5
gkr1 is a directory

Unix Programming & Compiler Design lab Page 23


Task 3:
3 (a). Write a shell script to demonstrate the creation of a menu to display list of files, process
status, users of a system, current date, present working directory and exit from prompt (using
case statement).
AIM:To write a shell script to demonstrate the creation of a menu to display list of files,
process status, users of a system, current date, present working directory and exit from
prompt (using case statement).
Script:
echo “enter your choice”
read ch
echo “1-list of files 2-Process Status 3-Users of a system 4-Current date 5-present
working directory(pwd)”
case “$ch” in
1)echo “list of files”
ls
;;
2)echo “process status”
ps
;;
3)echo “Users of a system”
who
;;
4)echo “current date”
date
;;
5)echo “present working directory”
pwd
;;
default ) echo “invalid choice”
esac
OUTPUT:
enter your choice

Unix Programming & Compiler Design lab Page 24


1-list of files 2-process status 3-users of system 4-current date 5-present working directory
4
date Tue Sep 22 10:05:22 IST 2016

3(b). Write an awk script to count the number of lines in a file that do not contain
vowels.
AIM: An awk script to find the number of lines in a file without vowels.
Script:
BEGIN{
printf "\t No. of lines in a given file "
FS= " "
}
#BODY
{
if($0 !~ /[aAeEiIoOuU]/)
{
nlines++;
}
}
END{
printf "\n Total no. of lines that do not contain vowels: %d\n",nlines}

OUTPUT:

$cat f1
hello
hai
my
sky

$awk –f pr8.awk f1
No. of lines in a given file :
Total no. of lines that do not contain vowels: 2

Unix Programming & Compiler Design lab Page 25


3(c). Write an awk script to find the number of characters, words and lines in a file.
AIM: An awk script to find the number of lines, characters, words in a file.
Script:
BEGIN{
printf "\t No. of lines, characters, words in a given file :\n "
FS= " "
}
#BODY
{
nlines++;
nwords=nwords+NF;
cchar=cchar+length($0);
}
END{
printf "No. of lines : %d \n No.of words :%d \n No. of words: %d\n",nlines,
nwords,cchar}

OUTPUT:
$cat f1
hello world
hai
my
sky

$awk –f pr9.awk f1
No. of lines, characters, words in a given file :
No.of lines : 5
No.of words: 19

Task 4:

Unix Programming & Compiler Design lab Page 26


4 (a). Write a c program that makes a copy of a file using standard I/O and system calls
AIM: Program to copy of a file using standard I/O and system calls.
Program:

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
void main()
{
int fd1,fd2,n=1;
char *buf;
fd1=open("f1",O_RDONLY);
fd2=open("f2",O_WRONLY|O_CREAT,S_IWUSR|S_IRUSR);
if((fd1== -1) || (fd2== -1))
printf("error");
else
{
while(n>0)
{
n=read(fd1,&buf,1);
write(fd2,&buf,1);
}
}
}

OUTPUT:

$ cat > f1
Welcome to Advanced UNIX programming lab
[3]+ Stopped cat >f1

$ gcc p10.c
$ ./a.out
$cat f1
Welcome to Advanced UNIX programming lab
$cat f2
Welcome to Advanced UNIX programming lab

4 (b). Implement in C the following UNIX commands using System calls

Unix Programming & Compiler Design lab Page 27


A. cat B. ls
A. cat
AIM: Implement in C the UNIX command cat.

Program:
#include<fcntl.h>
#include<stdlib.h>
#include<sys/stat.h>
#define BUFSIZE 1024
void main(int argc, char *argv[])
{
int fd1;
int n;
char buf[BUFSIZE];
fd1=open(argv[1],O_RDONLY);
while((n=read(fd1,buf,BUFSIZE))>0)
write(1,buf,n);
close(fd1);
}

OUTPUT:

$ gcc p11a.c
$ ./a.out f1 (given file name as argument)
Welcome to Advanced UNIX Programming lab

Unix Programming & Compiler Design lab Page 28


B. ls
AIM: Implement in C the UNIX command ls.

Program:
#include<fcntl.h>
#include<stdlib.h>
#include<dirent.h>
#include<stdio.h>
#define BUFSIZE 1024
void main(int argc, char *argv[])

{
DIR *dir;
struct dirent *direntry;
if((dir=opendir(argv[1]))==NULL)
exit(0);
while(direntry=readdir(dir))
printf("%s\n",direntry->d_name);
closedir(dir);
}

OUTPUT:

$ gcc p11b.c
$ ./a.out karuna (given directory name as argument)
.
..
f1
f2
gkr

4(c). Write a program that takes one or more file/directory names as command line
input and reports the following information on the file.

Unix Programming & Compiler Design lab Page 29


A. File type. B. Number of links.
C. Time of last access. D. Read, Write and Execute permissions.

AIM: Program to display file type, no. of links, time of last access and rwx permissions.

Program:
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#define BUFSIZE 1024
int main(int argc, char *argv[])
{
int i=1;
struct stat statbuf;
while(i<argc)
{
if(lstat(argv[i],&statbuf) == -1)
exit(0);
printf("File name : %s\n",argv[i]);
printf("File type and permissions : %o\n",statbuf.st_mode);
printf("No.of links : %d\n",statbuf.st_nlink);
printf("Time of last access : %d\n",ctime(&statbuf.st_atime));
i++;
}
}

OUTPUT:

$ gcc p12.c
$ ./a.out f1 (given file name as argument)
File name: f1
File type and permissions : 100664
No. of links : 1
Time of last access : 5990208

4(d). Write a C program that demonstrates redirection of standard output to a file.


Ex: ls > f1.

Unix Programming & Compiler Design lab Page 30


AIM: program for redirection of standard output to a file.

Program:

#include<fcntl.h>
#include<stdlib.h>
#include<dirent.h>
#include<string.h>
#include<unistd.h>
#include<sys/stat.h>
#define BUFSIZE 1024
void main(int argc, char *argv[])
{
DIR *dir;
int fd1;
struct dirent *direntry;
fd1=open("f3.txt",O_WRONLY|O_CREAT);
printf("%d",fd1);
if((dir=opendir(argv[1]))==NULL)
exit(0);
else
{
while(direntry=readdir(dir))
{
write(fd1,direntry->d_name, strlen(direntry->d_name));
}
}
closedir(dir);
}

OUTPUT:
$ gcc p15.c
$ ./a.out karuna (given directory name as argument)
$cat f2.txt
f1
f2
gkr

Task 5:

Unix Programming & Compiler Design lab Page 31


5(a). Write a C program to create a child process and allow the parent to display
“parent” and the child to display “child” on the screen.

AIM: program to display parent and child process

Program:
# include<stdio.h>
#include<sys/types.h>
void main( )
{
pid_t pid;
pid=fork( );
if (pid<0)
{
printf("unable to create a process ");
}
else if(pid >0)
{
printf("Parent Process …");
printf("Process id : %d\t Its parent id : %d \n", getpid( ),getppid( ));
}
else
{
printf("Child Process …");
printf("Process id : %d\t Its parent id : %d \n", getpid( ),getppid( ));
}
}

OUTPUT:

$ gcc p16.c
$ ./a.out

Parent Process…..
Procee id: 2255 Its parent id: 2678
Child Process…..
Procee id: 2980 Its parent id: 2255

Unix Programming & Compiler Design lab Page 32


5(b). Write a C program to create a Zombie process.

AIM: Program to create Zombie Process.

Program:
# include<stdio.h>
#include<sys/types.h>
void main( )
{
pid_t pid;
pid=fork( );
if (pid<0)
{
printf("unable to create a process ");
}
else if (pid==0)
{
printf("Child Process …");
printf("Process id : %d\t Its parent id : %d \n", getpid( ),getppid( ));
printf("Child Process terminated….");
}
else if(pid >0)
{
printf("Parent Process …");
for( ; ; );
}
}

OUTPUT:
$ gcc p17.c
$ ./a.out
Parent Process…..
Child Process…..
Procee id: 2980 Its parent id: 2255

Child Process terminated (because parent is not available)


$ps –el (it displays statue of process and shown the zombie status of child)
F S UID PID PPID C PRI NI ADDR S TTY
… …. …. ….. ….. ….. …. …. … ….
z … …. 2980 ….. ….. ….. … …. …. …. ……

Unix Programming & Compiler Design lab Page 33


5(c). Write a C program that illustrates how an orphan is created.

AIM: Program to create Zombie Process.

Program:
# include<stdio.h>
#include<sys/types.h>
void main( )
{
pid_t pid;
pid=fork( );
if (pid<0)
{
printf("unable to create a process ");
}
else if(pid==0)
{
printf("Child Process …");
printf("Process id : %d\t Its parent id : %d \n", getpid( ),getppid( ));
sleep(30);
printf("Process id : %d\t Its parent id : %d \n", getpid( ),getppid( ));
}
else
{
printf("Parent Process …");
printf("Process id : %d\t Its parent id : %d \n", getpid( ),getppid( ));
}
}

OUTPUT:

$ gcc p18.c
$ ./a.out

Parent Process…..
Procee id: 2255 Its parent id: 2678
Child Process…..
Procee id: 2980 Its parent id: 2255
(after sleep…..)
$ Procee id: 2980 Its parent id: 1 (orphan process parent is init process & id is 1)

Unix Programming & Compiler Design lab Page 34


5(d). Write a C program that illustrates suspending and resuming processes using
signals.

AIM: C program that illustrate suspending and resuming processes using signals.

Program:
#include<stdio.h>
#include<signal.h>
void alarmHandler(int);
void intHandler(int);
void main( )
{
signal(SIGINT,intHandler);
signal(SIGALRM,alarmHandler);
printf("alaram is set to 10 sec \n");
alarm(10);
printf("The process is paused for a while \n");
pause();
printf("The process is going to sleep \n");
sleep(10);
}

void intHandler(int sig)


{
signal(SIGINT, intHandler);
printf("interrupted signal is handled \n");
}

void alarmHandler(int sig)


{
signal(SIGALRM,alarmHandler);
printf("alarm signal is handled \n");
}

OUTPUT:
csedept@csedept-Lenovo-G570:~$ gcc p24.c
csedept@csedept-Lenovo-G570:~$ ./a.out
alaram is set to 10 sec
The process is paused for a while
^C interrupted signal is handled
The process is going to sleep
alarm signal is handled

Unix Programming & Compiler Design lab Page 35


Task 6:
6(a). Write a C program that illustrates how to execute two commands concurrently
with a command pipe. (Ex: - ls –l | sort)
AIM: Program to execute two commands concurrently with pipe.
Program:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
void main( )
{
int p1[2],p2[2],nbytes;
pid_t pid;
char string[]=”Hello World!\n”;
char readbuffer[80];
pipe(p1);
pipe(p2);
if(pipe(p1)<0 || pipe(p2) < 0)
printf("pipe creation error");
if (( childpid=fork())<0)
{
printf("cannot fork");
}
else if(pid == 0)
{
close(p1[0]);
close(p2[1]);
write(p1[1],string,(strlen(string)+1));
read(p2[0],readbuffer,100);
printf("child output :%s\n”,readbuffer);
exit(0);
}
else
{
close(p1[1]);
close(p2[0]);
nbytes=read(p1[0],readbuffer,sizeof(readbuffer));
printf("Received string at parent : %s\n”,readbuffer);
write(p2[1],”Thank you”,20);
} }
OUTPUT: $ gcc p19.c
$ ./a.out
Received string at parent : Hello World!
Child output : Thank you

Unix Programming & Compiler Design lab Page 36


6(b). Write C programs that illustrate communication between two unrelated processes
using named pipe.

AIM: Program implementing IPC using FIFO(named pipe).

Program:
#define FIFO1 "Fifo1"
#define FIFO2 "Fifo2"
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<fcntl.h>
#include<sys/stat.h>
void main( )
{
int childpid,wfd,rfd;
mknod(FIFO1,0666|S_IFIFO,0);
mknod(FIFO2,0666|S_IFIFO,0);
if (( childpid=fork())==-1)
{
printf("cannot fork");
}
else
if(childpid >0)
{
wfd=open(FIFO1,1);
rfd=open(FIFO2,0);
client(rfd,wfd);
while (wait((int *) 0 ) !=childpid);
close(rfd);
close(wfd);
unlink(FIFO1);
unlink(FIFO2);
}
else
{
rfd=open(FIFO1,0);
wfd=open(FIFO2,1);
server(rfd,wfd);
close(rfd);
close(wfd);
}
}
client(int readfd,int writefd)

Unix Programming & Compiler Design lab Page 37


{
int n;
char buff[1024];
printf ("enter file name");
if(fgets(buff,1024,stdin)==NULL)
printf("file name read error");
n=strlen(buff);
if(buff[n-1]=='\n')
n--;
if(write(writefd,buff,n)!=n)
printf("file name write error");
while((n=read(readfd,buff,1024))>0)
if(write(1,buff,n)!=n)
printf("data write error");
if(n<0)
printf("data error");
}
server(int readfd,int writefd)
{
char buff[1024],errmsg[50];
int n,fd;
n=read(readfd,buff,1024);
buff[n]='\0';
if((fd=open(buff,0))<0)
{
sprintf(buff,"file does not exist");
write(writefd,buff,1024);
}
else
{
while((n=read(fd,buff,1024))>0)
write(writefd,buff,n);
}
}

OUTPUT:
$ gcc p20.c
enter file name: f1 (server writes data into file f1)

Unix Programming & Compiler Design lab Page 38


TASK-7: Design a lexical analyzer for tokenizing an expression and identify comment lines in the
program.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void main(void)
{
char *s=(char *)calloc(sizeof(char),20000);
char *t=(char *)calloc(sizeof(char),20000);
char key[32][20]={"auto","break","case","char","const","continue","default"
,"do","double","else","enum","extern","float","for","goto"
,"if","int","long","register","return","short","signed",
"sizeof","static","struct","switch","typedef","union"
,"unsigned","void","volatile","while"};
int i,j,k=0,c;
char f[20],ch;
FILE *fp;
//clrscr();
printf("enter a file: ");
scanf("%s",f);
fp=fopen(f,"r");
if(fp==NULL)
printf("file cannot be opened");
else
{
while((ch=fgetc(fp))!=EOF)
{
*(s+k)=ch;
k++;
}
*(s+k)='\0';
}
printf("%s\n",s);
printf("------------------------------------------------------\n");
i=0;
x:while(*(s+i)!='\0')
{
j=0;c=0;
if(*(s+i)=='#')
{
i++;
while(*(s+i)!='\n')

Unix Programming & Compiler Design lab Page 39


{
printf("%c",*(s+i));
i++;
}
printf("is a pre processor directive\n");
i++;
}
else if(isalpha(*(s+i))||*(s+i)=='_')
{
*(t+j)=*(s+i);
i++; j++;
while((*(s+i)=='_'||isdigit(*(s+i))||isalpha(*(s+i)))&&*(s+i)!='\0')
{
*(t+j)=*(s+i);
i++;j++;
}
*(t+j)='\0';
for(k=0;k<32;k++)
if(strcmp(t,key[k])==0)
{
c=1;
break;
}
if(c==1)
printf("%s is a keyword\n",t);
else
{
if(*(s+i)=='(')
{
printf("%s is a method\n",t);
goto x;
}
else
printf("%s is an identifier\n",t);
}
}
else if(*(s+i)=='"')
{
printf("\"");
i++;
while(*(s+i)!='"')
{
printf("%c",*(s+i));
i++;

Unix Programming & Compiler Design lab Page 40


}

printf("\" is an argument \n");


i++;
}
else if((*(s+i)=='/'&&*(s+i+1)=='/')||(*(s+i)=='/'&&*(s+i+1)=='*'))
{
i++;
if(*(s+i)=='/')
{
i++;
while(*(s+i)!='\n')
printf("%c",*(s+i));
i++;
}
else if(*(s+i)=='*')
{
i++;
while(*(s+i)=='*'&&*(s+i+1)=='/')
{
if(*(s+i)=='\n')
printf("%c",*(s+i));

i++;
}
i=i+2;
}
printf("is a comment line\n");
}
else if(*(s+i)=='['||*(s+i)==']'||*(s+i)=='('||*(s+i)==')'||*(s+i)=='{'||*(s+i)=='}')
{
printf("%c is a special symbol\n",*(s+i));
i++;
}
else if(isdigit(*(s+i)))
{
if(isdigit(*(s+i))||*(s+i)=='.')
{
printf("%c",*(s+i));
i++;
while(isdigit(*(s+i))||*(s+i)=='.')
{
printf("%c",*(s+i));
i++;

Unix Programming & Compiler Design lab Page 41


}
printf(" is a number\n");
}
else if(isalpha(*(s+i)))
{
while(isalpha(*(s+i))||*(s+i)=='_')
{
printf("%c",*(s+i));
i++;
}
printf(" is an invalid token\n");
}
}
else if(*(s+i)=='='||*(s+i)=='+'||*(s+i)=='-'||*(s+i)=='*'||*(s+i)=='/'||*(s+i)=='%'||*(s+i)=='<'||
*(s+i)=='>'||*(s+i)=='&'||*(s+i)=='|')
{
printf("%c is an operator\n",*(s+i));
i++;
}
else if(*(s+i)==';')
{
printf("%c is terminator\n",*(s+i));
i++;
}
else
i++;
}
fclose(fp);
}
OUTPUT:
include<stdio.h> is a preprocessor directive
void is a keyword
main is a method
( is a special symbol
) is a special symbol
{ is a special symbol
int is a keyword
a is an identifier
; is terminator
printf is a method
( is a special symbol
“hai” is an argument
) is a special symbol
; is terminator

Unix Programming & Compiler Design lab Page 42


c is an identifier
= is an operator
a is an identifier
+ is an operator
100 is a number
; is terminator
} is a special symbol

TASK-8 : Implement top down parsing techniques.

a) Brute force technique b) RDP

#include<stdio.h>
#include<string.h>
void main()
{
char *s[20],temp;
char *a=(char *)calloc(sizeof(char),200);
char *t=(char *)calloc(sizeof(char),200);
int i=0,j=0,n,k=0,l=0,m=0,p=0;
printf("enter the no of productions: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
s[i]=(char *)calloc(sizeof(char),200);
printf("p%d:",i);
scanf("%s",s[i]);
}
printf("enter the string to derive: ");
scanf("%s",a);
printf("given productions\n");
for(i=0;i<n;i++)
{
printf("%s\n",s[i]);
}
i=0; j=0;
while(*(s[i]+j)!='>')
{
j++;
}
j++;
x:m=0;
while(*(s[i]+j)!='\0')

Unix Programming & Compiler Design lab Page 43


{
if(*(s[i]+j)=='/') break;
if(isupper(*(s[i]+j)))
{
temp=*(s[i]+j);
y:l=0;
k=0;
while(k<n)
{
if(temp==*(s[k]+l))
break;
k++;
}
while(*(s[k]+l)!='>')
{
l++;
}
l++;
if(isupper(*(s[k]+l)))
{
temp=*(s[k]+l);
goto y;
}
else
{
z: while(*(s[k]+l)!='\0')
{
if(*(s[k]+l)=='/') break;
else if(*(a+p)!=*(s[k]+l))
{
p++;
while(*(s[k]+l)!='\0')
{
if(*(s[k]+l)=='/')
{l++; p--; goto z; }
l++;
}
}
else if(isupper(*(s[k]+l)))
{
temp=*(s[k]+l);
goto y;
}
else

Unix Programming & Compiler Design lab Page 44


{
*(t+m)=*(s[k]+l);
p++;
printf("%c",*(t+m));
m++;
l++;
}
}
}
}
else
{ if(*(a+p)!=*(s[i]+j))
{
p++;
while(*(s[i]+j)!='\0')
{
if(*(s[i]+j)=='/')
{p--;j++; goto x; }
j++;
}
}
else
{
while(*(s[i]+j)!='\0')
{
if(*(s[i]+j)=='/')
break;
else if(isupper(*(s[i]+j)))
{
temp=*(s[i]+j);
goto y;
}
else
{
*(t+m)=*(s[i]+j);
printf("%c",*(t+m));
p++;
m++;
j++;
}
}
}
}
j++;

Unix Programming & Compiler Design lab Page 45


}
*(t+m)='\0';
if(strcmp(t,a)==0)
printf("\nthe string is parsed");
else
{
if(*(s[i]+j)=='/')
{
p=0;
j++;
goto x;
}
else
{
printf("\nString is not parsed");
}
}
}

OUTPUT:
……TO VALIDATE A STRING USING BRUTEFORCE TECHNIQUE……
S->cAd
A->ab/a
enter the input string
cad

string is valid

/*PROGRAM FOR RECURSSIVE DECENT PARSING*/


#include<stdio.h>
#include<conio.h>
int E();
int E1();
int T();
int T1();
int F();
char str[100];
int i=0;
void main()
{
clrscr();
printf("the rules are:");
printf("E->TE1\nE1->+TE1/@\nT->FT1\n");

Unix Programming & Compiler Design lab Page 46


printf("T->*FT1/@\nF->(E)/a/b");
printf("\n enter the input");
scanf("%s",str);

if(E())
{
if(str[i]=='$')
{
printf("String accepted");
}
else
{
printf("error");
getch();
}
}
else
printf("invalid expression");
getch();
}
int E()
{
if(T())
{
if(E1())
return 1;
else
return 0;
}
else
return 0;
}
int E1()
{
if(str[i]=='+')
{
i++;
if(T())
{
if(E1())
return 1;
else
return 0;
}

Unix Programming & Compiler Design lab Page 47


else
return 0;
}
return 1;
}

int T()
{
if(F())
{
if(T1())
return 1;
else
return 0;
}
return 0;
}
int T1()
{
if(str[i]=='*')
{
i++;
if(F())
{
if(T1())
return 1;
else
return 0;
}
else
return 0;
}
return 1;
}
int F()
{
if(str[i]=='(')
{
i++;
if(E())
{
if(str[i]==')')
{
i++;

Unix Programming & Compiler Design lab Page 48


return 1;
}
else
return 0;
}
else
return 0;
}
else if((str[i]=='a')||(str[i]=='b'))
{
i++;
return 1;
}
else
return 0;
}

OUTPUT:
Enter the input string
a+b
Valid input string
Enter the input string
+b
Invalid

TASK-9: Find the first set and follow of a given grammar.


#include<stdio.h>
void findFirst(char,int);
void findFollow(char,int);
void folTabOperation(char,int);
void firTabOperation(char,int);
struct firTab
{
int n;
char firT[5];
};
struct folTab
{
int n;
char folT[5];
};
struct folTab follow[5];
struct firTab first[5];
int col,np;

Unix Programming & Compiler Design lab Page 49


char a[8][8];
void main()
{
int i,j,c,cnt=0;
char ip;
char b[8];
printf("Enter no: of productions");
scanf("%d",&np);
printf("\n Enter %d productions in format E->TX,X->+TX",np);
for(i=0;i<np;i++)
{
scanf("%s",&a[i]);
}
for(i=0;i<np;i++)
{ c=0;
for(j=0;j<i+1;j++)
{
if(a[i][0] == b[j]) //Eliminating duplicate N.Ts
{
c=1;
break;
}
}
if(c !=1)
{
b[cnt] = a[i][0]; //moving N.Ts to b array
cnt++;
}
}
printf("\n");
for(i=0;i<cnt;i++)
{ col=1;
first[i].firT[0] = b[i];
first[i].n=0;
findFirst(b[i],i);
}
for(i=0;i<cnt;i++)
{col=1;
follow[i].folT[0] = b[i];
follow[i].n=0;
findFollow(b[i],i);
}
printf("\n");
/* printing of first*/

Unix Programming & Compiler Design lab Page 50


for(i=0;i<cnt;i++)
{
for(j=0;j<=first[i].n;j++)
{
if(j==0)
{ printf("\nFirst(%c) : {",first[i].firT[j]);
}
else
{
printf(" %c",first[i].firT[j]);
}
}
printf(" } ");
}
/* printing of follow */
for(i=0;i<cnt;i++)
{
for(j=0;j<=follow[i].n;j++)
{
if(j==0)
{
printf("Follow(%c) : {",follow[i].folT[j]);
}
else
{
printf(" %c",follow[i].folT[j]);
}
}
printf(" } ");
printf("\n");
}
}//main
/* Function for finding first */
void findFirst(char ip,int pos)
{
int i;
for(i=0;i<np;i++)
{
if(ip == a[i][0])
{
if(isupper(a[i][3]))
{
findFirst(a[i][3],pos);
}

Unix Programming & Compiler Design lab Page 51


else
{
first[pos].firT[col]=a[i][3];
first[pos].n++;
col++;
}
}
}
}
/* function for finding follow */
void findFollow(char ip,int row)
{ int i,j;
if(row==0 && col==1)
{ follow[row].folT[col]= '$';
col++;
follow[row].n++;
}
for(i=0;i<np;i++)
{
for(j=3;j<np-1;j++)
{
if(a[i][j] == ip)
{
if(a[i][j+1] == '\0')
{
if(a[i][j] != a[i][0])
{
folTabOperation(a[i][0],row);
}
}
else if(isupper(a[i][j+1]))
{ if(a[i][j+1] != a[i][0])
{
firTabOperation(a[i][j+1],row);
}
}
else
{ follow[row].folT[col] = a[i][j+1];
col++;
follow[row].n++;
}
}
}
}

Unix Programming & Compiler Design lab Page 52


}
void folTabOperation(char ip,int row)
{ int i,j;
for(i=0;i<5;i++)
{
if(ip == follow[i].folT[0])
{
for(j=1;j<=follow[i].n;j++)
{ follow[row].folT[col] =follow[i].folT[j];
col++;
follow[row].n++;
}
}
}
}
void firTabOperation(char ip,int row)
{ int i,j;
for(i=0;i<5;i++)
{ if(ip == first[i].firT[0])
{
for(j=1;j<=first[i].n;j++)
{ if(first[i].firT[j] != '0')
{ follow[row].folT[col] = first[i].firT[j];
follow[row].n++;
col++;
}
else
{ folTabOperation(ip,row);
}
}
}
}
}

/*

OUTPUT:
E->TX
X->+TX
X-.>#
T->FY
Y->*FY
Y->#

Unix Programming & Compiler Design lab Page 53


F->i
F->(E)

FIRST SET

E {,i,(}
T {i, ( }
X {+,#}
Y { *.#}
F { i,(}

FOLLOW SET

E { $,)}
X { $,)}
T { +,$,)}
Y { +,$,)}
F { *,+,$,)}
b) follow of a given grammar.
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
struct fir
{
int n;
char nt,first[5];
}fir[5];

struct fol
{
int n;
char nt,follow[5];
}fol[5];
int folp=0,n=6;
char p[6][10];

void firtab(int pos,char ip)


{
int i,j;
for(i=0;i<5;i++)
{
if(ip==fir[i].nt)
{

Unix Programming & Compiler Design lab Page 54


for(j=0;j<fir[i].n;j++)
{
fol[pos].follow[fol[pos].n]=fir[i].first[j];
fol[pos].n++;
}
}
}
}

void foltab(int pos,char ip)


{
int i,j;
for(i=0;i<5;i++)
{
if(ip==fol[i].nt)
{
for(j=0;j<fol[i].n;j++)
{
fol[pos].follow[fol[pos].n]=fol[i].follow[j];
fol[pos].n++;
}
}
}
}

void findfollow(char ip,int pos)


{
int i,j;
fol[0].nt=ip;
if(pos==0)
{
fol[0].follow[fol[0].n]='$';
fol[0].n++;
}
for(i=0;i<n;i++)
{
for(j=3;p[i][j]!='\0';j++)
{
if(ip==p[i][j])
{
if(isupper(p[i][j+1]) && p[i][j+1]!=ip)
firtab(pos,p[i][j+1]);
else if(p[i][j+1]=='\0')

Unix Programming & Compiler Design lab Page 55


foltab(pos,p[i][0]);
else
{
fol[pos].follow[fol[pos].n]=p[i][j+1];
fol[pos].n++;
}
}
}
}
}

void main()
{
int i,j;
char b[6];
strcpy(p[0],"E->TX");
strcpy(p[1],"X->+TX");
strcpy(p[2],"T->FY");
strcpy(p[3],"Y->*FY");
strcpy(p[4],"F->(E)");
strcpy(p[5],"F->i");
strcpy(b,"EXTYF");
fir[0].nt='X';
fir[0].n=1;
strcpy(fir[0].first,"+");
fir[0].nt='Y';
fir[0].n=1;
strcpy(fir[0].first,"*");
for(i=0;i<5;i++)
{
findfollow(b[i],folp);
folp++;
}
strcpy(fol[0].follow,"$)");
strcpy(fol[1].follow,"$)");
strcpy(fol[2].follow,"+");
strcpy(fol[3].follow,"+");
strcpy(fol[4].follow,"*");
printf("follow sets are\n");
for(i=0;i<5;i++)
{
//printf("%c-> ",fol[i].nt);
for(j=0;fol[i].follow[j]!='\0';j++)
printf("%c,",fol[i].follow[j]);

Unix Programming & Compiler Design lab Page 56


printf("\n");
}
}

FOLLOW SET

E { $,)}
X { $,)}
T { +,$,)}
Y { +,$,)}
F { *,+,$,)}

TASK-10 : Implement shift reduce parsing


#include<stdio.h>
#include<conio.h>
#include<string.h>
int i,j,l,n,top=0,k,p,sl;
char in[20],apro[20],pro[20][20],sta[20],stack[20];
int s[10];
void null();
void out();
void main()
{
clrscr();
printf("\n\t\tEnter the total no of production:\t");
scanf("%d",&n);
printf("\n\tEnter the production\n");
for(i=0;i<n;i++)
{
scanf("%s",pro[i]);
s[i]=strlen(pro[i])-3;
}
printf("\n\t\tEnter the input string end with $:\t");
scanf("\n%s",in);
printf("\n\t\tInput string is:%s",in);
printf("\n\nStack\tInput\t\tAction\n");
printf("\n\n---------------------------------------------\n");
stack[top]='$';
l=0;
out();
while(in[l]!='$')
null();
if(stack[top]==pro[0][0] && stack[top+1]=='\0')
printf("\t\taccept\n");

Unix Programming & Compiler Design lab Page 57


else
printf("error\n");
getch();
}
void null()
{
int p=0,m;
if(in[l]!='$')
stack[++top]=in[l++];
printf("\t\tshift:%c\n",stack[top]);
out();
while(1)
{
if(stack[top-p]=='$')
break;
else
{
for(m=top-p,k=0;m<=top;m++,k++)
sta[k]=stack[m];
sta[k]='\0';
sl=strlen(sta);
for(i=0;i<n;i++)
{
//printf("s1=%d\t%d",sl,s[0]);
if(sl==s[i])
{
for(j=3,k=0;pro[i][j]!='\0';j++)
{
apro[k]=pro[i][j];
k++;
}
apro[k]='\0';
if((strcmp(sta,apro))==0)
{
top=top-p;
p=0;
stack[top]=pro[i][0];
stack[top+1]='\0';
printf("\t\t%s\n",pro[i]);
out();

}
}
}

Unix Programming & Compiler Design lab Page 58


}
p++;
}
}
void out()
{
int i;
for(i=0;i<=top;i++)
printf("%c",stack[i]);
printf("\t");
for(i=l;in[i]!='\0';i++)
printf("%c",in[i]);
}
OUTPUT:
Enter then total no of productions: 3

Enter the production


E->E+E
E->E*E
E->i
Enter the input string end with $: i+i$

Input string is:i+i$

Stack Input Action

--------------------------------------------------------------
$ i+i$ shift:i
$i +i$ E->i
$E +i$ shift:+
$E+ i$ shift:i
$E+i $ E->i
$E+E $ E->E+E
$E $ accept

TASK-11 /* Program to generate intermediate code for given statements*/


#include<stdio.h>

#include<string.h>

int i,ch,j,l,addr=100;

Unix Programming & Compiler Design lab Page 59


char ex[10],exp[10],exp1[5],id1[5],op[5],id2[5];

void main()

char ex1[5],ex2[5];

while(1)

printf("\n1.assignment\n2.arithmetic\n3.relational\n4.Exit\nEnter the choice:");

scanf("%d",&ch);

switch(ch)

case 1:

printf("\nEnter the expression with assignment operator:");

scanf("%s",exp);

l=strlen(exp);

ex2[0]='\0';

i=0;

while(exp[i]!='=')

i++;

strncat(ex2,exp,i);

strrev(exp);

Unix Programming & Compiler Design lab Page 60


ex1[0]='\0';

strncat(ex1,exp,l-(i+1));

strrev(ex1);

printf("Three address code:\ntemp=%s\n%s=temp\n",ex1,ex2);

break;

case 2:

printf("\nEnter the expression with arithmetic operator:");

scanf("%s",ex);

strcpy(exp,ex);

l=strlen(exp);

exp1[0]='\0';

for(i=0;i<l;i++)

if(exp[i]=='+'||exp[i]=='-')

if(exp[i+2]=='/'||exp[i+2]=='*')

strrev(exp);

j=l-i-1;

strncat(exp1,exp,j);

strrev(exp1);

printf("Three address code:\ntemp=%s\ntemp1=%c%ctemp\n",exp1,exp[j+1],exp[j]);

Unix Programming & Compiler Design lab Page 61


break;

else

strncat(exp1,exp,i+2);

printf("Three address code:\ntemp=%s\ntemp1=%c%ctemp\n",exp1,exp[j],exp[j+1]);

break;

else if(exp[i]=='/'||exp[i]=='*')

strncat(exp1,exp,i+2);

printf("Three address code:\ntemp=%s\ntemp1=%c%ctemp\n",exp1,exp[j],exp[j+1]);

break;

break;

case 3:

printf("Enter the expression with id1 relop and id2");

scanf("%s%s%s",id1,op,id2);

if(((strcmp(op,"<")==0)||(strcmp(op,">")==0)||(strcmp(op,"<=")==0)||(strcmp(op,">=")==0)||
(strcmp(op,"==")==0)||(strcmp(op,"!=")==0))==0)

printf("Expression is error");

Unix Programming & Compiler Design lab Page 62


else

printf("\n%d\tif %s%s%s goto %d",addr,id1,op,id2,addr+3);

addr++;

printf("\n%d\t T:=0",addr);

addr++;

printf("\n%d\t goto %d",addr,addr+2);

addr++;

printf("\n%d\t T:=1",addr);

break;

case 4:exit(0);

strrev(char* str)

int len,i,temp;

len=strlen(str)-1;

for(i=0;i<strlen(str)/2;i++)

temp=str[i];

Unix Programming & Compiler Design lab Page 63


str[i]=str[len];

str[len--]=temp;

return(str);

}
OUTPUT:
1.ASSIGNMENT
2.ARITHMETIC
3.RELATIONAL
4.EXIT
Enter the choice:1

Enter the expression with assignment operator:a=b


Three address code:
temp=b
a=temp

1.ASSIGNMENT
2.ARITHMETIC
3.RELATIONAL
4.EXIT
Enter the choice:_

/* PROGRAM TO GENERATE TARGET CODE FOR GIVEN STATEMENTS*/


#include<stdio.h>
#include<string.h>
struct regis
{
char var;
}reg[10];
int noreg=0;
char st[10][10];
int nost;
char* opcode[10]={"add","sub","mul","div"};
char oper[10]={'+','-','*','/'};
void main()
{
int i,j,k,regno2=0,regno1=1;

Unix Programming & Compiler Design lab Page 64


int flag=0;
printf("\nenter the no. of statements:");
scanf("%d",&nost);
printf("enter the statements:");
for(i=0;i<nost;i++)
{
scanf("%s",st[i]);
}
for(k=0;k<nost-1;k++)
{
for(j=2;j<5;j++)
{
if(st[k][j]!=st[k+1][j])
flag=1;
}
}
printf("\n\nstatements \t \t targetcode");
for(i=0;i<nost;i++)
{
printf("\n\t%s",st[i]);
if((!regno1==isinregister(st[i][2])))
{
printf("\n\t\t\t\t MOV %c,r%d",st[i][2],++noreg);
reg[noreg].var=st[i][2];
regno1=noreg;
}
if((!regno2==isinregister(st[i][4])))
{
printf("\n\t\t\t\t %s r%d,r%d\n",toopcode(st[i][3]),regno2,regno1);
reg[regno1].var=st[i][0];
}
else
{
printf("\n\t\t\t\t %s %c,r%d\n\n",toopcode(st[i][3]),st[i][4],regno1);
reg[regno1].var=st[i][0];
}

printf("\t\t\t\t MOV r%d,%c\n",regno1,st[i][0]);

if(flag==0)
{
printf("\t%s\t\t\tMOV r%d,%c\n",st[i+1],regno1,st[i+1][0]);
break;
}

Unix Programming & Compiler Design lab Page 65


}
}
char* toopcode(char opert)
{
int i;
for(i=0;i<4;i++)
{
if(oper[i]==opert)
{
return(opcode[i]);
}
}
}

int isinregister(char var)


{
int i;
for(i=1;i<=noreg;i++)
{
if(var==reg[i].var)
{
return(i);
}
}
return(0);
}

OUTPUT:
TO GENERATE OPTMIZED TARGET MACHINE CODE FOR AN INTERMEDIATE
CODE
Enter the no. of statements:2
Enter the statements:a=b+c
x=b+c
If the machine architecture is having the following format
OPERATIONS SOURCE TARGET
ADD var/reg var/reg :--> MOV b,r1 ,variable b contents are moved to register r1

Tstatements targetcode
a=b+c
MOV b,r1
ADD c,r1
MOV r1,a
x=b+c MOV r1,x

Unix Programming & Compiler Design lab Page 66


CODE GENERATION COMPLETED

Task-12(a). LEX program to count the number of lines, words and letters, capital letters,
small letters and digits in a file.
Algorithm:
Read each character from the text file :

 Is it a capital letter in English? [A-Z] : increment capital letter count by 1.


 Is it a small letter in English? [a-z] : increment small letter count by 1

 Is it [0-9]? increment digit count by 1.

 All other characters (like '!', '@','&') are counted as special characters

 How to count the number of lines? we simply count the encounters of '\n'
<newline>character.

 To count the number of words we count white spaces and tab character(of course,
newline characters too..)

Program:
%{
#include<stdio.h>
int lines=0, words=0,s_letters=0,c_letters=0, num=0, spl_char=0,total=0;
%}
%%

\n { lines++; words++;}
[\t ' '] words++;
[A-Z] c_letters++;
[a-z] s_letters++;
[0-9] num++;
. spl_char++;
%%

main(void)
{
yyin= fopen("myfile.txt","r");
yylex();
total=s_letters+c_letters+num+spl_char;
printf(" This File contains ...");
printf("\n\t%d lines", lines);
printf("\n\t%dwords",words);
printf("\n\t%d small letters", s_letters);
printf("\n\t%d capital letters",c_letters);
printf("\n\t%d digits", num);
printf("\n\t%d special characters",spl_char);
printf("\n\tIn total %d characters.\n",total);
}

Unix Programming & Compiler Design lab Page 67


int yywrap()
{
return(1);
}

Output:
 Let the 'myfile.txt' contains this.

                         This is my 1st lex program!!!


                         Cheers!! It works!!:)
This file contains..
2 lines
9 words
30 small letters
3 capital letters
1 digits
9 special characters
In total 43 characters.

Task12(c): Design a simple arithmetic calculator: Use LEX and YACC

%{
#include
int op=0,i;
floata,b;
%}

dig [0-9]+|([0-9]*)"."([0-9]+)
add "+"
sub "-"
mul "*"
div "/"
pow "^"
ln \n

%%
{dig} {digi();} /*** digi() is a user defined function ***/
{add} {op=1;}
{sub} {op=2;}
{mul} {op=3;}
{div} {op=4;}
{pow} {op=5;}
{ln} {printf("\n the result :%f\n\n",a);}

%%
digi()
{
if(op==0)
a=atof(yytext); /*** atof() is used to convert the ASCII input to float***/
else

Unix Programming & Compiler Design lab Page 68


{
b=atof(yytext);
switch(op)
{
case 1:a=a+b;
break;
case 2:a=a-b;
break;
case 3:a=a*b;
break;
case 4:a=a/b;
break;
case 5:for(i=a;b>1;b--)
a=a*i;
break;
}
op=0;
}
}
main(int argv,char *argc[])
{
yylex();
}
yywrap()
{
return 1;
}

Output:
7+5
The result :12.000

/* Yacc program implementing a simple calculator */

%{
#include<stdio.h>
#include<ctype.h>
%}
%token num
%left '+''-'
%left '*''/'
%right '^'
%%
s:e'\n'{printf("%d",$1);}
e:    e '+' e{$$=$1+$3;}
 |e '-' e{$$=$1-$3;}
 |e '*' e{$$=$1*$3;}
 |e '/' e{$$=$1/$3;}
 |e '^' e {
  int i,j=$1;

Unix Programming & Compiler Design lab Page 69


  for(i=1;i<$3;i++)
  {
  j=j*$1;
  $$=j;
  }
  }
 |'('e')'{$$=$2;}
 |num1;
num1:num1 num{$$ = $1*10 + $2;}
 |num
 ;
%%
yylex()
{
int c;
c=getchar();
if(isdigit(c))
{
yylval=c-'0';
return num;
}
return c;
}
int main()
{
yyparse();
return 1;
}
int yyerror()
{
return 1;
}
int yywrap()
{
return 1;
}
output:
2+5
7

Unix Programming & Compiler Design lab Page 70

You might also like