限制 xargs 读取 stdin 到缓冲区
看起来 xargs 从 stdin 读取输入行,即使它已经运行了它可以运行的最大进程数。
这是一个例子:
#!/bin/bash
function xTrigger()
{
for ii in `seq 1 100`; do echo $ii; sleep 2; done
}
function xRunner()
{
sleep 10;
echo $1;
}
export -f xTrigger
export -f xRunner
bash -c "xTrigger" | xargs -n 1 -P 1 -i bash -c "xRunner {}"
在开始上述过程20秒后,我killall xTrigger
,所以但是xargs已经缓冲了xTrigger打印的所有内容,所以xRunner继续打印1..10。我想要的是它只打印 1,2
无论如何,我们可以改变这种行为并让 xargs 仅在它想要启动新命令时从 stdin 读取,以便 xTrigger 会在 echo 语句处等待,直到 xargs从中读取?我的标准输入具有非常动态的内容,因此这将非常有用。
尝试坚持使用 xargs 只是因为它稳定且优雅。仅当没有简单的方法使用 xargs 时才需要编写额外的代码。
感谢您的帮助!
It looks like xargs reads input lines from stdin, even when it is already running maximum number of process that it can run.
Here is an example:
#!/bin/bash
function xTrigger()
{
for ii in `seq 1 100`; do echo $ii; sleep 2; done
}
function xRunner()
{
sleep 10;
echo $1;
}
export -f xTrigger
export -f xRunner
bash -c "xTrigger" | xargs -n 1 -P 1 -i bash -c "xRunner {}"
20 seconds after starting above process, I killall xTrigger
, so but xargs has buffered everything xTrigger printed, so xRunner continued to print 1..10. What I want is for it to print only 1,2
Is there anyway by which we can change this behaviour and get xargs to read from stdin only when it wants to start a new command, so that xTrigger would wait at the echo statement until xargs reads from it? My stdin has very dynamic content so this would be very useful.
Trying to stick to xargs just because it would be stable and elegent. Want to write extra code only if there is no easy way of doing it with xargs.
Thanks for all your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
难道你不需要杀死xTrigger()的Bash PID吗?
Don't you have to kill the Bash PID of xTrigger()?
在我的系统上,如果 xargs 正在运行的作业之一以非零返回代码退出,则默认情况下 xargs 将停止。因此,您应该将信号发送到正在运行 XRunner 的 bash pid。
On my system, xargs will by default halt if one of the jobs it is running exits with a non-zero return code. Therefore, you should be sending the signal to the bash pid that is running XRunner.
仅当没有“bash -c xRunner”作业运行时,xTrigger 才会生成下一个触发器。现在效果很好:
Got xTrigger to to generate next trigger only when there are no 'bash -c xRunner' jobs running. Works great now: