Luki Luki - 7 days ago 5
C Question

Using pipes to pass data between child processes in C

My homework task is to write a C program that creates 4 child processes and each child has to do something with an integer number and send it to the next child that does something else with it and the last one has to print the changed value. I have to use anonymous pipes to communicate between children. Parent process has no other work than to open pipes for children. I have written the program, but the problem is I get funny output when I try to print the number using the last child. It prints out 8 numbers instead of one (actually one of them is the right one). The part of code is following:

int pipe1[2];
int pipe2[2];
int pipe3[2];
pipe(pipe1);
pipe(pipe2);
pipe(pipe3);

int j;

close(pipe1[1]); //close pipes for writing on parent process
close(pipe2[1]);
close(pipe3[1]);

for (j = 0; j < 4; j++) {
switch(fork()) {
case 0:
if (j == 0) {
int value = 100;
write(pipe1[1], &value, sizeof(int));
close(pipe1[1]);
}
else if (j == 1) {
int value;
read(pipe1[0], &value, sizeof(int));
close(pipe1[0]);
value = value * 10;
write(pipe2[1], &value, sizeof(int));
close(pipe2[1]);
}
//and so on until the last process
else if (j == 3) {
int value;
read(pipe3[0], &value, sizeof(int));
char buf[4] = {0};
memset(buf, 0, sizeof(buf));
snprintf(buf, sizeof(value), "%d ", value);
write(1, buf, strlen(buf));
}
break;
}
}
close(pipe1[0]);
close(pipe2[0]);
close(pipe3[0]);
sleep(1);

int k;

for (k = 0; k < 4; k++) {
wait(0);
}


What do I have to do for this case, just to get one (and the proper one) output?

Answer

What do you think happens when one of your child processes executes the break statement in the code you presented? Hint: it doesn't exit.

Additionally, I'm doubtful that your pipes can work quite like that. You close the write ends of two of them (one of those twice) before forking any children. Those will not magically be reopened for the children, so their whole pipes are useless.