So in my program, the user gives three arguments. Then, I pipe it into three children.
Two children all do their own calculations, then exits. The last child displays the results.
The parent waits for all children to finish, then it simply terminates the program.
A summary of what the children do:
inputs are a, b, c.
child0: c0 = a*b
child1: c1 = b*c
overview: printf("%d %d", c0, c1);
I can't figure out how to get the overview to print out correctly. It keeps printing out weird corrupted characters or boxes.
Anyone have any advice on how to do it correctly? I read a book, but it only went over in detail single child-parent pipes. This deals with multiple children, and I guess that's where I got confused. Thanks for your help!
Code below:
int main(int argc, char *argv[]) {
int fd[4];
int a, b, c, c0, c1, status;
char char0[10];
char char1[10];
pid_t child0;
pid_t child1;
pid_t overview;
// Set argv to ints
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
// Pipe
pipe(fd);
// child0
if((child0 = fork()) == 0) {
close(fd[2]);
c0 = a*b;
sprintf(char0, "%d", c0);
write(fd[0], char0, 10);
close(fd[0]);
exit(0);
}
// child1
if((child1 = fork()) == 0) {
close(fd[2]);
c1 = b*c;
sprintf(char1, "%d", c1);
write(fd[1], char1, 10);
close(fd[1]);
exit(0);
}
// overview
if((overview = fork()) == 0) {
close(fd[0]);
close(fd[1]);
read(fd[2], char0, 10);
read(fd[2], char1, 10);
printf("%s %s", char0, char1); //Prints weird stuff??
close(fd[2]);
exit(0);
}
// Wait for children to finish
waitpid(child0, &status, 0);
waitpid(child1, &status, 0);
waitpid(overview, &status, 0);
exit(0);
}