我試圖用FIFO做一些簡單的事情:讀取行,但不是一次全部完成,而且它意外地「沒有工作」。在shell腳本中使用mkfifo
這是OK:
$ f=$(mktemp -u)
$ mkfifo $f
$ { seq 5 > $f; } &
[1] 2486
$ while read line; do echo $line; done < $f
1
2
3
4
5
[1]+ Done { seq 10 > $f; }
但如果我嘗試一個接一個讀取線,第一讀取成功,第二次讀取掛起。
$ { seq 5 > $f; } &
[1] 2527
$ read line < $f; echo $line
1
[1]+ Done { seq 5 > $f; }
$ read line < $f; echo $line
[hangs here...]
有人可以解釋這一點嗎?爲什麼我不能一一讀完所有5行?其餘數據發生了什麼?
我發現我可以讀行由行,如果我創建了一個文件描述符重定向FIFO:
$ { seq 5 > $f; } &
[1] 2732
$ exec 3<$f
[1]+ Done { seq 5 > $f; }
$ read -u 3 line && echo $line || echo no more data
1
$ read -u 3 line && echo $line || echo no more data
2
$ read -u 3 line && echo $line || echo no more data
3
$ read -u 3 line && echo $line || echo no more data
4
$ read -u 3 line && echo $line || echo no more data
5
$ read -u 3 line && echo $line || echo no more data
no more data
$ exec 3<&-
我還是不明白中間的情景。誰能解釋一下?
版本信息:
$ bash --version
GNU bash, version 4.2.25(1)-release (i686-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ mkfifo --version
mkfifo (GNU coreutils) 8.13
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by David MacKenzie.
這可能與版本和bash vs ksh或??有關。你可以添加該信息嗎? (在任何情況下,我都不會知道答案;-()。本季度最有趣的問題! – shellter
在OSX Mavericks和Ubuntu VirtualBox下的行爲完全一樣 –
您的第三種情況不能被斥責 – devnull