gpt4 book ai didi

shell - 使用 bash 异步消耗管道

转载 作者:行者123 更新时间:2023-12-04 15:57:35 25 4
gpt4 key购买 nike

我有一个像这样的 bash 脚本

data_generator_that_never_guits | while read data 
do
an_expensive_process_with data
done

第一个进程连续生成事件(以不规则的间隔),需要在它们可用时进行处理。这个脚本的一个问题是 read on 消耗了一行输出;并且由于处理非常昂贵,我希望它消耗当前可用的所有数据。另一方面,如果有新数据可用,则必须立即开始处理。简而言之,我想做这样的事情
data_generator_that_never_guits | while read_all_available data 
do
an_expensive_process_with data
done

如果没有数据可用于消费或将所有当前可用数据复制到变量,则命令 read_all_available 将等待。如果数据不包含整行,那就完全没问题了。基本上,我正在寻找 read 的模拟,它会读取整个管道缓冲区,而不是只从管道中读取一行。

对于你们中间的好奇,问题的背景是我有一个构建脚本,它需要在源文件更改时触发重建。我想避免过于频繁地触发重建。请不要建议我使用 grunt、gulp 或其他可用的构建系统,它们不能很好地满足我的目的。

谢谢!

最佳答案

我想我在更好地了解 subshel​​l 的工作原理后找到了解决方案。该脚本似乎可以满足我的需求:

data_generator_that_never_guits | while true 
do
# wait until next element becomes available
read LINE
# consume any remaining elements — a small timeout ensures that
# rapidly fired events are batched together
while read -t 1 LINE; do true; done
# the data buffer is empty, launch the process
an_expensive_process
done

可以将所有读取的行收集到一个批次中,但此时我并不真正关心它们的内容,所以我没有费心去弄清楚那部分:)

添加于 25.09.2014

这是最后一个子程序,以防有一天它对某人有用:
flushpipe() {
# wait until the next line becomes available
read -d "" buffer
# consume any remaining elements — a small timeout ensures that
# rapidly fired events are batched together
while read -d "" -t 1 line; do buffer="$buffer\n$line"; done
echo $buffer
}

像这样使用:
data_generator_that_never_guits | while true 
do
# wait until data becomes available
data=$(flushpipe)
# the data buffer is empty, launch the process
an_expensive_process_with data
done

关于shell - 使用 bash 异步消耗管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26019751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com