How a pipe shell handles an infinite loop

Whenever I need to limit the output of shell commands, I use less to paginate:

cat file_with_long_content | less

which works fine and dandy, but I wonder what works less, even if the output never ends, consider the following script in inf.sh :

while true; do date; done

then i run

sh inf.sh | less

And it can still paginate pages again, so is it right to say that the streams broadcast the result, rather than waiting for the command to complete before the result is displayed?

+4
source share
3 answers

Yes, when running sh inf.sh | less sh inf.sh | less two commands run in parallel. Data written to the pipe by the first process is buffered (by the core) until it is read by the second. If the buffer is full (that is, if the first command writes to the channel faster than the second can read), the next write operation will be blocked until additional space is available. A similar condition occurs when reading from an empty channel: if the channel buffer is empty, but the input end is still open, reading will block additional data.

See the pipe (7) manual for details.

+7
source

It is right. Pipes are flows .

You can program your own version of the less tool in very few lines of C code. Take the time to do this, including a brief study of files and pipes, and you will understand with understanding to answer your own question and much more :).

+1
source

There also an informative article by Alexander Sandler entitled "How less it processes its input!"

See: Time taken by the less command to output results

+1
source

All Articles