Luki Luki - 1 year ago 77
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];

int j;

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

for (j = 0; j < 4; j++) {
switch(fork()) {
case 0:
if (j == 0) {
int value = 100;
write(pipe1[1], &value, sizeof(int));
else if (j == 1) {
int value;
read(pipe1[0], &value, sizeof(int));
value = value * 10;
write(pipe2[1], &value, sizeof(int));
//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));

int k;

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

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download