壳管如何处理无限循环 [英] how shell pipe handles infinite loop

查看:77
本文介绍了壳管如何处理无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我需要限制shell命令的输出时,我都会减少对结果的分页:

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

cat file_with_long_content | less

可以正常工作,但我很好奇的是,即使输出永无止境,仍然无法正常工作,请考虑在inf.sh文件中包含以下脚本:

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

然后我跑步

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?

推荐答案

是的,当您运行sh inf.sh | less时,这两个命令是并行运行的.由第一个进程写入管道的数据被缓冲(由内核),直到被第二个进程读取.如果缓冲区已满(即,如果第一个命令写入管道的速度快于第二个命令读取的速度),则下一个写入操作将阻塞,直到有更多空间可用为止.从空管道读取数据时也会发生类似的情况:如果管道缓冲区为空,但输入端仍处于打开状态,则读取将阻塞以获取更多数据.

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.

请参见 pipe(7)有关详细信息的手册.

See the pipe(7) manual for details.

这篇关于壳管如何处理无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆