Linux 如何保持FIFO打开以供阅读?

Linux 如何保持FIFO打开以供阅读?,linux,bash,mkfifo,Linux,Bash,Mkfifo,我正在尝试重定向程序的stdin和stdout。我目前正在尝试一个bash模型,但我得到了一些奇怪的行为 我有以下资料: mkfifo in mkfifo out tail -f out ./test.sh < in > out echo "foo" > in echo "bar > in 我还有以下脚本test.sh #!/bin/bash while read line; do echo "I read ${lin

我正在尝试重定向程序的stdin和stdout。我目前正在尝试一个bash模型,但我得到了一些奇怪的行为

我有以下资料:

mkfifo in
mkfifo out
tail -f out
./test.sh < in > out
echo "foo" > in
echo "bar > in
我还有以下脚本test.sh

#!/bin/bash

while read line; do
  echo "I read ${line}"
done < /dev/stdin
在终端2中,我执行以下操作:

mkfifo in
mkfifo out
tail -f out
./test.sh < in > out
echo "foo" > in
echo "bar > in

但是,在终端1中,我没有看到“I read foo”后面跟着“I read bar”,而是在第一次回音之后什么也没有得到,在第二次回音之后是两行,然后终端2中的test.sh程序退出。如何防止退出,以便继续发送test.sh输入?另外,我如何才能让test.sh的输出刷新到终端1中的tail-f,而不是在程序终止时缓冲然后转储?

在包含两个
echo
命令的单个复合命令上使用重定向

{
  echo "foo"
  echo "bar"
} > in
如果您希望在交互执行命令时保持
in
处于打开状态,请使用
exec
在另一个文件描述符上打开
in

exec 3> in      # Open in on file descriptor 3
echo "foo" >&3  # Write to file descriptor 3 instead of standard output
echo "bar" >&3  # "
exec 3>&-       # Close file descriptor 3

请注意,中的
exec 3>将被阻止,直到有东西(
test.sh
在您的情况下)打开
in
进行读取,并且由于缓冲,在关闭文件描述符3之前,您可能看不到
tail-f out
的任何输出。

后者正是我想要的——谢谢!