如何实时读取Bash的子过程的Stdout
我有一个简单的C ++程序,每1秒钟以每1秒的速度计数从0到10。当值增加时,将其写入stdout。该程序有意使用printf而不是std :: cout。 我想从BASH脚本调用此程序,并在将其写入STDOUT时对值执行一些功能(例如ECHO)。 但是,我的脚本等待程序终止,然后同时处理所有值。
C ++ prog:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int ctr = 0;
for (int i = 0; i < 10; ++i)
{
printf("%i\n", ctr++);
sleep(1);
}
return 0;
}
bash脚本:
#!/bin/bash
for c in $(./script-test)
do
echo $c
done
是否有另一种方法可以读取程序的输出,这将实时访问它,而不是等待该过程终止。 注意:C ++程序是一个演示示例 - 我正在使用的实际程序也使用printf,但是我无法更改此代码,因此解决方案需要在BASH脚本中。
非常感谢 斯图尔特
I have a simple C++ program that counts from 0 to 10 with an increment every 1 second. When the value is incremented, it is written to stdout. This program intentionally uses printf rather than std::cout.
I want to call this program from a bash script, and perform some function (eg echo) on the value when it is written to stdout.
However, my script waits for the program to terminate, and then process all the values at the same time.
C++ prog:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int ctr = 0;
for (int i = 0; i < 10; ++i)
{
printf("%i\n", ctr++);
sleep(1);
}
return 0;
}
Bash script:
#!/bin/bash
for c in $(./script-test)
do
echo $c
done
Is there another way to read the output of my program, that will access it in real time, rather than wait for for the process to terminate.
Note: the C++ program is a demo sample - the actual program I am using also uses printf, but I am not able to make changes to this code, hence the solution needs to be in the bash script.
Many thanks,
Stuart
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您正确观察到的那样,
$(命令)
等待命令
的整个输出,将输出拆分,仅此后, for loop 开始。要尽快读取输出,请在阅读时使用
:
或者,如果您需要从循环内部访问变量,并且您的系统支持
&lt;()
As you correctly observed,
$(command)
waits for the entire output ofcommand
, splits that output, and only after that, thefor
loop starts.To read output as soon as is available, use
while read
:or, if you need to access variables from inside the loop afterwards, and your system supports
<()
您可能会使用管道更幸运:
You might be more lucky using a pipe: