0% found this document useful (0 votes)
71 views27 pages

Test Related Document

The document discusses various YACC programs to recognize different grammars and evaluate expressions: 1. A YACC program to recognize valid arithmetic expressions and evaluate them using operators like +, -, *, /. 2. A program to recognize nested IF control statements and count the levels of nesting. 3. A program to recognize strings that belong to the grammar {anbn | n>=0} and verify various sample strings. 4. A program to recognize valid C variable declarations and definitions. The document also provides examples of signal handling in C using kill(), waiting for child processes using wait(), I/O system calls like reading, writing and creating files, and using shared memory for inter

Uploaded by

The BigBrad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views27 pages

Test Related Document

The document discusses various YACC programs to recognize different grammars and evaluate expressions: 1. A YACC program to recognize valid arithmetic expressions and evaluate them using operators like +, -, *, /. 2. A program to recognize nested IF control statements and count the levels of nesting. 3. A program to recognize strings that belong to the grammar {anbn | n>=0} and verify various sample strings. 4. A program to recognize valid C variable declarations and definitions. The document also provides examples of signal handling in C using kill(), waiting for child processes using wait(), I/O system calls like reading, writing and creating files, and using shared memory for inter

Uploaded by

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

YACC PROGRAMS

1) Recognize a valid and Evaluate Arithmetic expression that use


operators +, -, *, /
validarith.l
%{
#include<stdio.h>
#include"y.tab.h"
int yylval;
%}
%%
[0-9]* { yylval=atoi(yytext);
return ID;
}
[\+\*\-\/] {return yytext[0];}
\n {return 0;}
. {return yytext[0];}
%%

int yywrap() {return 1;}


validarith.y
%{
#include<stdio.h>
#include<stdlib.h>
int yylex();
void yyerror(char *msg);
%}

%token ID

%left '+' '-'


%left '*' '/'
%left '(' ')'
%%
start: E {printf("Valid arithmetic expression\n");
printf("Result=%d\n",$1);
exit(0);}
;
E: E '+' E { $$ = $1 + $3 ;}
| E '-' E { $$ = $1 - $3 ;}
| E '*' E { $$ = $1 * $3 ;}
| E '/' E { $$ = $1 / $3 ;}
| '('E')' { $$ = $2;}
| ID { $$ = $1;}
;
%%
void yyerror(char *msg) {
printf("Invalid expression\n");
exit(0);
}

int main() {
printf("Enter arithmetic expression:\n");
yyparse();
return 0;
}
Output:
Enter arithmetic expression:
(1*2)/(1+1)
Valid arithmetic expression
Result=1

2) Recognize nested IF control statements and displays the number of


levels of nesting in the nested IF.
nested_if.l
%{
#include"y.tab.h"
%}

id [a-zA-Z][a-zA-Z0-9_]*
num [0-9]+
relop ("<"|">"|"<="|">="|"=="|"!=")
unaryop ("++"|"--")
binaryop ("+"|"-"|"*"|"/")

%%
"if" {return IF;}
"else" {return ELSE;}
{id} {return ID;}
{num} {return NUM;}
{relop} {return RELOP;}
{unaryop} {return UNARYOP;}
{binaryop} {return BINARYOP;}
[ \t\n] ;
. {return yytext[0];}
%%

int yywrap() {return 1;}


nested_if.y
%{
#include<stdio.h>
#include<stdlib.h>

int yylex();
void yyerror(char *msg);

extern FILE *yyin;


int count = 0;
%}

%token IF ELSE ID RELOP UNARYOP BINARYOP NUM

%%
start: if_stmt {printf("Valid if statement\n");}
;
if_stmt: IF '(' expr ')' '{'
statements
'}'
{count++;}
| IF '(' expr ')' '{'
statements
'}' ELSE '{'
statements
'}'
{count++;}
;
expr: ID
| NUM
| ID '=' expr
| expr BINARYOP expr
| expr UNARYOP
| expr RELOP expr
|
;
statements: statement statements
|
;
statement: if_stmt
| expr ';'
;
%%
void yyerror(char *msg) {
printf("Invalid statement\n");
exit(0);
}

int main() {
yyin = fopen("input.txt", "r");
if(!yyin) {
printf("File not found!\n");
return 0;
}

do {
yyparse();
} while (!feof(yyin));

printf("IF statements: %d\n", count);


return 0;
}
input.txt
if (x >= 5 ) {
if (x < 10) {
y++;
} else {
y--;
}
}
Output:
Valid if statement
IF statements: 2
3. Design a YACC program to recognize the grammar {an b \ n>=0}.
Verify the following string belongs to this grammar: (i) a (ii) ab (iii)
aaab (iv) abb.

LEX:(an_b.l)

%{
#include"y.tab.h"
%}

%%
[a] {return A;}
[b] {return B;}
[ \t] ; // Ignore spaces and tabs
\n {return NL;}
. {return yytext[0];}
%%

int yywrap() {return 1;}

YACC:(an_b.y)

%{
#include<stdio.h>
#include<stdlib.h>

int yylex();
void yyerror(char *msg);
%}

%token A B NL
%%
start: AN B NL {printf("String accepted\n"); exit(0);}
;
AN: A AN
|
;
%%

void yyerror(char *msg) {


printf("String rejected\n");
exit(0);
}

int main() {
printf("Enter string of a's and b's:\n");
yyparse();
return 0;
}

OUTPUT:
i)a
Enter string of a’s and b’s:
a
String rejected

ii)ab
Enter string of a’s and b’s:
ab
String accepted
iii)aaab
Enter string of a’s and b’s:
aaab
String accepted

iv)abb
Enter string of a’s and b’s:
abb
String rejected

4) Recognize valid declaration and definition statement in C

Lex File:

%{
#include"y.tab.h"
%}

%%
(int|float|char) {return BUILTIN;}
[a-zA-Z]([a-zA-Z0-9_])* {return ID;}
, return COMMA;
; return SC;
\n return NL;
%%

int yywrap() {
return 1;
}
Yacc File:

%{
#include<stdio.h>
#include<stdlib.h>
int yylex();
void yyerror(char *str);
%}

%token ID BUILTIN SC NL COMMA

%%
start: BUILTIN varlist SC NL {
printf("valid");
exit(0);
}
;
varlist:varlist COMMA ID|ID
|
;
%%
void yyerror(char *str){
printf("Error in declaration or definition");
exit(0);
}
int main(){
printf("Enter variable declaration\n");
yyparse();
return 0;
}
Output:

Enter variable declaration


int a,b,c;
Valid

Enter variable declaration


Float x;
invalid

SYSTEM CALLS

8)e)SIGNAL HANDLING USING KILL


#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

// function declaration
void sighup();
void sigint();
void sigquit();

// driver code
void main()
{
int pid;

/* get child process */


if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}

if (pid == 0) { /* child */
signal(SIGHUP, sighup);
signal(SIGINT, sigint);
signal(SIGQUIT, sigquit);
for (;;)
; /* loop for ever */
}

else /* parent */
{ /* pid hold id of child */
printf("\nPARENT: sending SIGHUP\n");
kill(pid, SIGHUP);

sleep(3); /* pause for 3 secs */


printf("\nPARENT: sending SIGINT\n");
kill(pid, SIGINT);

sleep(3); /* pause for 3 secs */


printf("\nPARENT: sending SIGQUIT\n");
kill(pid, SIGQUIT);
sleep(3);
}
}
// sighup() function definition
void sighup()

{
signal(SIGHUP, sighup); /* reset signal */
printf("CHILD: I have received a SIGHUP\n\n");
}

// sigint() function definition


void sigint()

{
signal(SIGINT, sigint); /* reset signal */
printf("CHILD: I have received a SIGINT\n\n");
}

// sigquit() function definition


void sigquit()
{
printf("parent killed the child.\n");
exit(0);
}
OUTPUT:-
PARENT: sending SIGHUP
CHILD: I have received a SIGHUP

PARENT: sending SIGINT


CHILD: I have received a SIGINT

PARENT: sending SIGQUIT


parent killed the child.

8)f)Wait Command
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
pid_t pid;
pid = fork();

if(pid==0)
{
printf("Child process : \n");
printf("I'm child with id : %d\n",getpid());
printf("My parent with id : %d\n",getppid());
printf("\nChild process completed...\n");
}
else
{

printf("Parent process : \n");


printf("I'm parent with id : %d\n",getpid());
printf("My child id : %d\n",pid);
wait(0);
printf("\nParent process completed...\n");

}
return 0;
}
OUTPUT:-
Parent process :
I'm parent with id : 241
My child id : 242
Child process :
I'm child with id : 242
My parent with id : 241

Child process completed...

Parent process completed...

I/O SYSTEM CALLS

9)
a) Reading from a file
b) Writing into a file
c) File Creation
#include<stdio.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
char buf[30];
int n,f1,f2;
//creating a file
f1=open("input.txt",O_RDONLY);
//reading from a file
n=read(f1,buf,30);
f2=open("output.txt",O_CREAT|O_WRONLY,0642);
//writing to a file
write(f2,buf,n);
write(1,buf,n);
return 0;
}
OUTPUT:-
abcd12345
input.txt abcd12345
Output.txt abcd12345

SHARED MEMORY

//Program to illustrate shared memory implementation.


#include<stdio.h>
#include<sys/shm.h>
#include<sys/stat.h>
void main()
{
int segment_id;
char* shared_mem;
const int size=4096;
segment_id=shmget(IPC_PRIVATE,size,S_IRUSR|S_IWUSR);
shared_mem=(char*)shmat(segment_id,NULL,0);
sprintf(shared_mem,"Shared Data");//Writing a message to shared
memory
printf("%s\n",shared_mem);//Printing the string from the shared
memory
shmdt(shared_mem);//Detach the shared memory segment
shmctl(segment_id,IPC_RMID,NULL);//Removing the shared
memory segment
}
OUTPUT:Shared Data

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<sys/mman.h>
int main()
{
void *ps;
char buffer[10];
int shmid1;
shmid1=shm_open("OS",O_CREAT|O_RDWR, 0666);
ftruncate(shmid1,1024);
ps=mmap(0,1024,PROT_WRITE, MAP_SHARED, shmid1, 0);
printf("Key of the shared memory: %d\n",shmid1);
printf("process attached at:%p\n",ps);
printf("enter some data to write to shared memory\n");
read(0,buffer,10);
sprintf(ps,"%s",buffer);
return 0;
}
OUTPUT:Key of the shared memory: 3
process attached at:0x7f4942b1d000
enter some data to write to shared memory
this data

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<sys/mman.h>
int main()
{
void *ps;
char buffer[10];
int shmid1;
shmid1=shm_open("OS",O_RDONLY, 0666);
ftruncate(shmid1,1024);
ps=mmap(0,1024,PROT_READ, MAP_SHARED, shmid1, 0);
printf("Key of the shared memory: %d\n",shmid1);
printf("process attached at:%p\n",ps);
printf("%s",(char*)ps);
shm_unlink("OS");
return 0;
}
OUTPUT:Key of the shared memory: 3
process attached at:0x7f6668c0a000
this data

-------------------------------------------------------------------------------
//Write a program to generate and print Fibonacci series with the
following
requirements:
- Parent program should create a child and distribute the task of
generating
Fibonacci no to its child.
- The code for generating Fibonacci no. should reside in different
program.
- Child should write the generated Fibonacci sequence to a shared
memory.
- Parent process has to print by retrieving the Fibonacci sequence
from the
shared memory.
a) Implement the above using shmget and shmat
b) Implement the above using shm_open and mmap
Note: Shared object should be removed at the end in the program
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int fi(int k){
if(k==1)
return 0;
if(k==2)
return 1;
else
return fi(k-1)+fi(k-2);
}
int main(int argc, char *argv[])
{
int i;
pid_t pid;
int k;
int n1,n2,n3;
const int SIZE = 4096;
//const char *name = "SharedMem";

int shmid;
void *ptr;
if (argc > 1)
{
sscanf(argv[1], "%d", &i);
if (i < 0)
{
printf("Error input: %d\n", i);
return 0;
}
}
else
{
return 1;
}

pid = fork();

if (pid == 0)
{ k=1;
int f=0;
shmid = shmget((key_t)1122,1024, 0666|IPC_CREAT);
//ftruncate(shm_fd, SIZE);
ptr = shmat(shmid,0,0666);
printf("CHILD:\n");
while (k<=i)
{
f=fi(k);
sprintf(ptr,"%d ", f);
printf("%d ", f);
ptr += strlen(ptr);
k++;
}
shmdt(ptr);
}
if (pid > 0)
{
wait(NULL);
printf("PARENT: child completed\n");

shmid = shmget((key_t)1122,1024, 0666);


ptr = shmat(shmid,0,0666);
printf("Parent printing:\n");

printf("%s ", (char *)ptr);


//shm_unlink(name);
}
return 0;
}

OUTPUT:
CHILD:
0 1 1 2 3 5 8 PARENT: child completed
Parent printing:
0112358

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
int main(int argc, char *argv[])
{
int i;
pid_t pid;
int k;
int n1,n2,n3;
const int SIZE = 4096;
const char *name = "SharedMem";

int shm_fd;
void *ptr;
if (argc > 1)
{
sscanf(argv[1], "%d", &i);
if (i < 1)
{
printf("Error input: %d\n", i);
return 0;
}
}
else
{
return 1;
}

pid = fork();
if (pid == 0)
{ k=2;
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, SIZE);
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
printf("CHILD:\n");
n1=0;

n2=1;

sprintf(ptr,"%d ",n1);
ptr+=strlen(ptr);
printf("%d ",n1);
sprintf(ptr,"%d ",n2);
ptr+=strlen(ptr);
printf("%d ",n2);
while (k!=i)
{
n3=n1+n2;
sprintf(ptr,"%d ", n3);
printf("%d ", n3);
n1=n2;
n2=n3;
ptr += strlen(ptr);
k++;}

}
else if (pid > 0)
{
wait(NULL);
printf("PARENT: child completed\n");
shm_fd = shm_open(name, O_RDONLY, 0666);
ptr = mmap(0, SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
printf("Parent printing:\n");

printf("%s ", (char *)ptr);


shm_unlink(name);
}
return 0;
}

OUTPUT:
CHILD:
0 1 1 2 3 5 8 PARENT: child completed
Parent printing:
0112358

SIMULATION OF ls,rm,grep

ls_sim.c
// Simulation of ls command
#include<stdio.h>
#include<sys/types.h>
#include<dirent.h>
#include<stdlib.h>
void main(int argc, char *argv[])
{
DIR *dp;
struct dirent *dirp;
if(argc<2)
{
printf("\n You not passing the directory\n");
exit(1);
}
if((dp=opendir(argv[1]))==NULL)
{
printf("\nCannot open it does't exist %s file!\n",argv[1]);
exit(1);
}
while((dirp=readdir(dp))!=NULL)
printf("%s\n",dirp->d_name);
closedir(dp);
}
Input: ./a.out _codeblocks
Output:
apowern.c
insertionsort.c
mergesort.c
poly.c
quicksort.c
grep_sim.c
// Simulation of grep command
#include<stdio.h>
#include<string.h>
void main()
{
char fn[10],pat[10],temp[200];
FILE *fp;
printf("Enter file name\n");
scanf("%s",fn);
printf("Enter pattern to be searched\n");
scanf("%s",pat);
fp=fopen(fn,"r");
while(!feof(fp))
{
fgets(temp,1000,fp);
if(strstr(temp,pat))
printf("%s",temp);
}
fclose(fp);
}

Input: ./a.out
Output:
Enter file name
aaa.txt
Enter pattern to be searched
delete
Hello . Iam getting deleted .

rm_sim.c
// Simulation of rm command
#include<stdio.h>
#include<fcntl.h>
void main()
{
char fn[10];
printf("Enter source filename\n");
scanf("%s",fn);
if(remove(fn)==0)
printf("File removed\n");
else
printf("File cannot be removed\n");
}
Input ./a.out
Output : Enter source filename
Out.txt
File removed

You might also like