
yes "test" | grep -m3 "test"
印刷
test
test
test
然後終止。也是如此
yes "test" | while read line; do echo $line; done | grep -m3 "test"
和
yes "test" | while read line; do echo $line; done | grep -E "*" | grep -m3 "test"
但
yes "test" | while read line; do echo $line | grep -E "*"; done | grep -m3 "test"
印刷
test
test
test
然後掛起。這裡發生了什麼事?
答案1
在
是的「測試」|讀取行時;回顯 $line;完成 | grep -E“*”| grep -m3“測試”有四個進程,分別是 running 、運行該循環的
yes
shell 程式、和。管道中的最後一個進程在三個匹配後終止,關閉其輸入管道的讀取端。然後,管道以提前終止管道的通常方式透過 s 鏈終止,因為管道的每個階段最終都會寫入損壞的管道。while
grep
grep
SIGPIPE
在
是的「測試」|讀取行時;回顯 $line | grep -E "*";完成 | grep -m3“測試”有三個進程正在運行
yes
,分別是 shell 程式 和grep
。但第二個進程,也就是運行 shell 程式的進程,不斷地產生兩個進程更遠子進程,一個執行該操作echo
,另一個運行另一個grep
實例。正是後一個進程發送了SIGPIPE
和不是運行shell程序的進程。畢竟,後一個過程實際上是在寫入損壞的管道。
這樣做的結果是管道的第二階段,即運行該while
循環的 shell,永遠不會本身終止SIGPIPE
並繼續運行,生成子管道;一遍又一遍。它看到它產生的子管道以 當然 終止,但對於運行循環的SIGPIPE
shell 來說,while
不是終止循環的原因。