Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how shell pipe handles infinite loop

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?

like image 945
Andreas Wong Avatar asked Feb 24 '23 11:02

Andreas Wong


1 Answers

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.

like image 161
adl Avatar answered Feb 26 '23 20:02

adl