how shell pipe handles infinite loop

∥☆過路亽.° 提交于 2019-12-23 12:09:21

问题


Whenever I need to limit shell command output, I use less to paginate the results:

cat file_with_long_content | less

which works fine and dandy, but what I'm curious about is, less still works even if the output is never ending, consider having the following script in inf.sh file:

while true; do date; done

then I run

sh inf.sh | less

And it's still able to again paginate the results, so is it correct to say that pipe streams the result rather than waiting for the command to finish before outputting the result?


回答1:


Yes, when you run sh inf.sh | less the two commands are run in parallel. Data written into the pipe by the first process is buffered (by the kernel) until it is read by the second. If the buffer is full (i.e., if the first command writes to the pipe faster than the second can read) then the next write operation will block until further space is available. A similar condition occurs when reading from an empty pipe: if the pipe buffer is empty but the input end is still open, a read will block for more data.

See the pipe(7) manual for details.




回答2:


It is correct. Pipes are streams.

You can code your own version of the less tool in very few lines of C code. Take the time to do it, including a short research on files and pipes, and you'll emerge with the understanding to answer your own question and more :).




回答3:


There's also an informative article by Alexander Sandler called "How less processes its input"!

See: Time taken by `less` command to show output



来源:https://stackoverflow.com/questions/6839809/how-shell-pipe-handles-infinite-loop

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