在 C 中使用管道在 child 个进程之间传递数据

Using pipes to pass data between child processes in C

我的作业任务是编写一个 C 程序,它创建 4 个 child 进程,每个 child 必须用一个整数做一些事情并将它发送到下一个 child用它做其他事情,最后一个必须打印更改后的值。我必须使用匿名管道在 children 之间进行通信。 Parent 进程除了为 children 打开管道外没有其他工作。我已经编写了程序,但问题是当我尝试使用最后一个 child 打印数字时,我得到了有趣的输出。它打印出 8 个数字而不是一个(实际上其中一个是正确的)。部分代码如下:

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);
}

对于这种情况,我需要做什么才能得到一个(正确的)输出?

当您的 child 进程之一执行您提供的代码中的 break 语句时,您认为会发生什么?提示:它不会退出。

另外,我怀疑你的管道是否能像那样工作。在 分叉任何 children 之前,关闭其中两个(其中一个两次)的写端 。那些不会为 children 神奇地重新打开,所以他们的整个管道都没有用。