为什么从fifo文件读取-n将丢失shell中的数据

时间:2015-11-18 07:02:39

标签: bash shell fifo mkfifo

首先我做一个fifo

mkfifo a.fifo

然后我回应了一些东西

echo 1 > a.fifo

打开另一个终端,并添加某个

echo 2 > a.fifo

当然,这两个都被封锁了,然后我从fifofile中读到了

read -n1 < a.fifo

所有人都被释放了,我只有一个,而另一个人的遗失......

我的问题是为什么会发生这种情况,如何在不丢失数据的情况下逐一从fifo文件中获取内容?

THX

1 个答案:

答案 0 :(得分:2)

通过read -n1 < a.fifo,你

  1. 已打开a.fifo以供阅读
  2. 阅读一个字符
  3. 已关闭a.fifo
  4. 在两端关闭一个fifo,在两端关闭它。

    将它打开,直到你不再需要它为止。

    exec 3< a.fifo    # open for reading, assign fd 3
    read -r line1 <&3 # read one line from fd 3
    read -r line2 <&3 # read one line from fd 3
    exec 3<&-         # close fd 3
    

    在另一端:

    exec 3> a.fifo       # open for writing, assign fd 3
    printf 'hello\n' >&3 # write a line to fd 3
    printf 'wolrd\n' >&3 # write a line to fd 3
    exec 3>&-            # close fd 3
    

    有关重定向的更多信息,请参阅http://wiki.bash-hackers.org/howto/redirection_tutorial