I was writing a code in which I created two processes, handler.c and calculate.c, which communicate using a named pipe. The handler.c recieves the operands and operator as command-line arguments and sends them to calculate.c, then reads the result and prints it. The calculate.c reads the operands and operator from the pipe, performs the calculation, and then writes the result to the pipe.
The problem is that when I read the result value from the pipe in handler.c, it always gives the same wrong value (822096384) no matter what I do. Below are the codes.
HANDLER.C
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
int main(int argc, char* argv[])
{
char* name = argv[1];// pipe name
int a, b;
int fd = open(name, O_RDWR);
a=atoi(argv[3]);
b=atoi(argv[4]);
write(fd, &a, sizeof(int));
sleep(1);
write(fd, &b, sizeof(int));
sleep(1);
write(fd, argv[2], sizeof(argv[2]));
int res = 0;
sleep(1);
read(fd, &res, sizeof(int)); //it read the wrong value i.e. 822096384
printf("%d", res);
printf("\n %s %s %s = %d\n", argv[3], argv[2], argv[4], res);
close(fd);
return 0;
}
CALCULATE.C
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
int main(int argc, char* argv[])
{
char* name = argv[1];
int res = 0;
int a,b;
char o;
int fd = open(name, O_RDWR);
read(fd, &a, sizeof(int));
printf("op1: %d ", a);
sleep(1);
read(fd, &b, sizeof(int));
printf("op2: %d ", b);
sleep(1);
read(fd, &o, sizeof(char));
printf("operator: %c ", o);
if(strcmp(&o, "+") == 0)//if(o = '+')
{
res = a + b;
}
else if(strcmp(&o, "/") == 0)
{
res = a / b;
}
else if(strcmp(&o, "-") == 0)
{
res = a - b;
}
else if(strcmp(&o, "*") == 0)
{
res = a * b;
}
printf("result: %d\n", res); //here res have the correct value
write(fd, &res, sizeof(res));
close(fd);
return 0;
}
Output of Hander.c
--bash
User@V-Ubuntu:~/Desktop/pipes$ ./handler pipe + 2 1
822096384
2 + 1 = 822096384
Output of Calculate.c
--bash
User@V-Ubuntu:~/Desktop/pipes$ ./calculate pipe
op1: 2 op2: 1 operator: + result 3