Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

bash - Correct behavior of pipe operator in linux

As the pipe operator is unidirectional and takes output from one command and uses it as input for another. I typed

sleep 5 | echo "Hello World"

I expected the sleep process to complete first and then print "Hello World", but actually the opposite happens where Hello World is printed and then sleep command is executed.

Can some one explain why this happens?

question from:https://stackoverflow.com/questions/65889678/correct-behavior-of-pipe-operator-in-linux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The pipe operator runs both processes concurrently. If the second process needs to read input, it will wait for the first process to write something to the pipe.

But echo doesn't read input, so it doesn't wait.

If you instead wrote

sleep 5 | { read _; echo "Hello World"; }

the output would be delayed because read waits for something to be available in the pipe (in this case it will just read EOF because sleep doesn't write anything to stdout).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...