Multiple unix pipes not working

我的未来我决定 提交于 2020-01-15 11:15:52

问题


This first pipeline works fine (printing "c"):

echo "a" | sed 's/a/b/' | sed 's/b/c/'

This one does not do what I expect (nothing gets printed when I feed an "a" into my fifo ):

mkfifo fifo;
cat fifo | sed 's/a/b/' | sed 's/b/c/' 

However, if I remove the second "sed" command from the latter pipeline, I do get a "b" printed. I think my understanding of pipes and redirects must be too simplistic. Can someone explain to me how to fix the 2nd case so that I can run two successive commands on the contents of the fifo?

(note this isn't a problem specific to fifo, the same behavior occurs with netcat too. I posted a similar question about netcat but got no answers)


回答1:


Buffering. sed is changing it's buffering depending on whether the output is a tty or not. When you have two sed's, the first determines it's output is not a tty so it is buffering. So when you have:

cat fifo | sed 's/a/b'

sed is not buffering as it's output is to a tty so you see the data but when you have:

cat fifo | sed 's/a/b' | sed 's/c/d'

the first sed is buffering the data. Depending on the specific sed you are running, there are different ways to disable buffering. GNU sed has the --unbuffered option while BSD sed has the -l option to switch to line buffering.



来源:https://stackoverflow.com/questions/25112713/multiple-unix-pipes-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!