我已经用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中,我这样运行它: ```sh 命令示例 ```
$ 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
没有任何输出:Bash while
循环无法从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
的输出可以通过OUT
传递到Bash while
循环中,并在控制台上打印出来。
a.out有什么问题呢?
stdout
重定向到管道后,IO 流将不再是行缓冲而是完全缓冲。您也可以使用setbuf
将其更改为行缓冲。 - user339222