0

为了自学,我想用管道连接 2 个程序。第一个程序接受输入,将其置顶并打印到屏幕上,在此示例中,第一个程序被执行但没有输入输出可能。我必须如何更改第二个程序中的管道 close() 函数才能获得结果。

4

1 回答 1

1

写入后立即关闭输出管道,或在每个字符写入后将第一个程序修改为 fflush(stdout)(因为 std(in|out) 第二个程序的缓冲性质卡在读取上,第一个程序等待输入,因为它没有得到 EOF - 第二个程序的 close() 将 EOF 发送到第一个,第一个终止,并在终止时自动刷新标准输出)。

int main(int argc, char** argv) {
  pid_t pid;
  int fi[2];
  int fo[2];

  char c;

  if (pipe(fi) < 0)
    perror("pipe");
  if (pipe(fo) < 0)
    perror("pipe");

  switch ( fork() ) {
  case -1:
    exit(1);
  case 0:
    dup2(fi[0], STDIN_FILENO);
    close(fi[1]);
    dup2(fo[1], STDOUT_FILENO);
    close(fo[0]);
    execlp("pipes1", "pipes1",(char *)NULL);

  default:
    close(fi[0]);
    close(fo[1]);
    break;
  }

  write(fi[1], "t", 1);
  close(fi[1]);
  read(fo[0], &c, 1);
  printf("%c\n", c);
  close(fo[0]);

  return 0;
}
于 2012-04-25T10:54:34.530 回答