bash - 最小化 bash 中延迟循环处理的缓冲管道

标签 bash shell loops redirect pipe

我有一个循环,它将随着日志文件的增长而跟踪它,搜索模式并对其使用react。问题是我在某个地方遇到了一个缓冲区,延迟了循环获取输入的时间,我相信这是由于 tail -f 并将日志通过管道传输到 grep 造成的。 p>

不起作用

while read l; do echo "l = |$l|"; done < <(tail -f $logfile | grep $pattern)

我已将 $logfile 设置为 fifo,并且必须 cat realfile.log > $logfile 3 或 4 次 (realfile.log大约 2K 行),在缓冲区似乎已填满并且通过循环立即处理这些行之前。

如果我从重定向的标准输入中删除 grep $pattern,该文件将按预期进行处理。

有效

while read l; do echo "l = |$l|"; done < <(tail -f $logfile)

也有效

while read l; do echo "l = |$l|"; done < <(tail $logfile | grep $pattern)

是否 tail 没有对 -f 上的写入进行 fsync()'ing

最佳答案

答案如下:

If I remove the grep $pattern from the redirected stdin, the file is processed as expected.

grep 缓冲导致延迟的输出。使用 grep--line-buffered 选项禁用缓冲。

引用man grep:

   --line-buffered
          Use  line  buffering  on  output.   This can cause a performance
          penalty.

关于bash - 最小化 bash 中延迟循环处理的缓冲管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19384464/

相关文章:

bash - 如何在 heredoc 部分设置和扩展变量

linux - 有没有办法在 bash 脚本中的 awk 语句中定义用户定义的函数?

c - 用于执行shell指令的shell代码

bash - 使用命令行将所有空文件复制到文件夹中

list - 如何在 dbt jinja 中将两个表连接到字典中

PHP 循环遍历 MySQL 函数返回的数组

bash - 如何使用 Bash 递归地创建不存在的子目录?

linux - AWK 比较两个文件输出匹配行中的两列 - 匹配中缺少行

bash - 如何指定 Bourne shell(不是 sh)

bash - 简单的 6 行 bash 脚本 while 循环...出了什么问题?