我在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);
}
}
Run Code Online (Sandbox Code Playgroud)
从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
Run Code Online (Sandbox Code Playgroud)
并且没有产生输出: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
Run Code Online (Sandbox Code Playgroud)
最后一行打印在stderr的控制台上.
cat与a.out不同的输出能够穿过OUT并到达Bash while循环,然后将其打印在控制台上.
a.out有什么问题?