We are going to write a calculator program to compute math equations using pipes
ID: 3556639 • Letter: W
Question
We are going to write a calculator program to compute math equations using pipes - program needs to fork() as many times as needed and use pipes to communicate to children. Equation specified in the first line of the data file will determine this setup. Once the setup is done, parent task reads the data from the data file and pumps into various pipes in parallel and results come back to main task using another pipe.
add, subtract, multiply & divide are the available tools in ~veerasam/students/proj5 directory (web-link) - you can copy them to your working directory to use with your project. All tasks use standard input stream 0 to read the first argument, use stream 3 to read 2nd argument and use standard output stream 1 for output. Main task uses the pipe stream numbers directly since it needs standard I/O streams to communicate with the user.
Here is an example: configuration diagram for computing "a - b * c" looks like the following. Note that the whole equation is processed left to right. No need to worry about operator precedence since that is not our focus here.
Sample data file content:
a - b * c
30 20 2
500 10 20
90 1 10
Usage: calculator < data.txt
Expected output:
20
9800
890
Explanation / Answer
/*pipe is a system call.allow the communication betwen two inter rellated processes. and pipe is unidirectional. so i have used two pipe one is for reading, writing of integers in the child process and other pipe is for sending back the caluclated result to parent process*/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int fd1[2],fd2[2]; // two pipes
pid_t pid;
int result,r1,n1,n2,n3,t1,t2,t3,op;
//Creating a pipe
r1= pipe (fd1);
r1= pipe (fd2);
if (r1< 0)
{
//failure in creating a pipe
perror("pipe");
exit (1);
}
//Creating a child process
pid = fork();
if (pid < 0)
{
//failure in creating a child
perror ("fork");
exit(2);
}
else if (pid>0)
{
//Parent process
printf ("Enter a three integers ");
scanf ("%d%d%d",&n1,&n2,&n3);
//Writing data to the pipe
write(fd1[1], &n1, sizeof(int));
write(fd1[1], &n2, sizeof(int));
write(fd1[1], &n3, sizeof(int));
/*reading the result by using other pipe fd2[1] */
read(fd2[0], &op, sizeof(int));
printf("%d ",op);
}
else if(pid==0)
{
//Child Process
//Reading message from the pipe
read(fd1[0], &t1, sizeof(int));
read(fd1[0], &t2, sizeof(int));
read(fd1[0], &t3, sizeof(int));
/*performing calculator operations*/
result=(t1-t2)*t3;
//After caluclating writing to other pipe i.e fd2[1]
write(fd2[1], &result, sizeof(int));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.