3

我用 C 语言编写了一个简单的 I/O 回显程序来测试一个更大的实际程序的问题。在这里,linux FD 重定向不起作用。

回显程序(又名a.out)是:

#include <stdio.h>

int main(int argc, char **argv) {
  char buff[10];
  while (1) {
    if (fgets(buff, 10, stdin) == NULL) break;
    printf("PRINT: %s \n", buff);
  }
}


在 Bash 中,我将其运行为:

$ mkfifo IN OUT
$ # this is a method to keep the pipes IN and OUT opened over time
$ while :; do read; echo Read: $REPLY >&2; sleep 1; done <OUT >IN &
$ a.out >OUT <IN &

$ echo xyz >IN

并且没有产生输出:Bashwhile循环无法从OUT.


让我们将这个 a.out 与 进行比较cat,它会按预期工作:

$ mkfifo IN OUT
$ while :; do read; echo Read: $REPLY >&2; sleep 1; done <OUT >IN &
$ cat >OUT <IN &

$ echo xyz >IN
Read: xyz

最后一行在控制台上打印到标准错误。 cat的输出与 a.out 不同,它能够穿越OUT并到达 Bashwhile循环,然后在控制台上打印它。
a.out 有什么问题?

4

1 回答 1

5

尝试添加fflush(stdout)之后printf(...)

于 2012-09-21T14:57:06.833 回答