My task is
a. A parent and two childs
b. Parent take data from the user
c. Send to a child for addition and subtraction.
d. Again take input from user and send to another child for multiplication and division.
e. First child process creates another child C3.
f. Both the childs send result to the child process C3 to show output.
g. Parent process after completion of each child process task kill the process.
I've write the following code but i don't know where I'm doing wrong, I tried to debug it but I do not know what is wrong with it, it not showing the multiplication and division result.
Here is my code:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
#include <stdlib.h>
int main()
{
int status = 0;
int pfds[2];
int pfds2[2];
int pfds3[2];
int pfds4[2];
int val = 0;
int val2 = 0;
pipe(pfds);
pipe(pfds2);
pipe(pfds3);
pipe(pfds4);
printf("Enter FIRST Number: ");
scanf("%i", &val);
printf("Enter SECOND Number: ");
scanf("%i", &val2);
if (fork() == 0)
{
//Child
printf("I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers\n");
read(pfds[0], &val, sizeof(val));
read(pfds2[0], &val2, sizeof(val));
int sum = val + val2;
int sub = val - val2;
write(pfds3[1], &sum, sizeof(val));
write(pfds4[1], &sub, sizeof(val));
if (fork() == 0)
{
read(pfds3[0], &val, sizeof(val));
printf("Sum Of Numbers Is : %i\n", val);
read(pfds4[0], &val, sizeof(val));
printf("Sub Of Numbers Is : %i\n", val);
read(pfds[0], &val, sizeof(val));
printf("Mul Of Numbers Is : %i\n", val);
read(pfds2[0], &val, sizeof(val));
printf("Div Of Numbers Is : %i\n", val);
exit(1);
}
else
{
wait(&status);
}
exit(1);
}
else
{
if (fork() == 0)
{
//Child2
printf("I'm Child 2 and I'm Calculating Multiplication and Division Of Number\n");
read(pfds[0], &val, sizeof(val));
read(pfds2[0], &val2, sizeof(val));
int mul = val * val2;
int div = val / val2;
write(pfds[1], &mul, sizeof(val));
write(pfds2[1], &div, sizeof(val));
exit(0);
}
else
{
//wait(&status);
write(pfds[1], &val, sizeof(val));
write(pfds2[1], &val2, sizeof(val));
wait(&status);
} //else1
} //else2
} //main
It's giving me the following output:
Enter FIRST Number: 4
Enter SECOND Number: 2
I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers
I'm Child 2 and I'm Calculating Multiplication and Division Of Number
Sum Of Numbers Is : 6
Sub Of Numbers Is : 2
If someone can help thankyou very much.