简体   繁体   English

永久获取C ++中运行的Shell命令的输出

[英]Get permanently the output from a shell command running in C++

I want to get the output from a shell command (my_program). 我想从shell命令(my_program)获得输出。 Here is a example taken from this site: 下面是采取了比如这个网站:

#include <iostream>
#include <stdio.h>

using namespace std;

int main() {
   FILE *in;
   char buff[512];

   if(!(in = popen("my_program", "r"))){
      return 1;
   }

   while(fgets(buff, sizeof(buff), in)!=NULL){
      cout << buff;
   }
   pclose(in);

   return 0;
}

The problem: 问题:

I want to run my program permanently and get the output while the program is still running, NOT only get the output from the program once. 我想永久运行程序并在程序仍在运行时获取输出,而不仅仅是从程序中获取输出。

Any idea? 任何想法?

Thanks in advanced. 提前致谢。

Your question is somewhat unclear but I suspect that the problem is buffer and the answer flushing: The way I understand is the program my_program produced outputs occassionally and the program you show should kick into action when my_program prints something. 您的问题尚不清楚,但我怀疑问题是缓冲区和答案刷新:据我了解,程序my_program偶尔my_program生成输出,并且当my_program打印某些内容时,您显示的程序应my_program Further I suspect that this program doesn't produce a lot of output in total, eg less than 4k. 此外,我怀疑该程序不会产生很多输出,例如少于4k。

The problem is that most implementations buffer standard output differently depending of whether this is directed to a "console" or something else: when writing to the console output tends to be line-buffer while other destinations buffer substantially bigger buffers. 问题在于,大多数实现对标准输出的缓冲取决于它是指向“控制台”还是其他东西:当写入控制台输出时,它倾向于行缓冲,而其他目标则缓冲更大的缓冲。 However, the buffer can be explicitly flushed, reducing the performance of the output substantially. 但是,可以显式刷新缓冲区,从而大大降低输出的性能。 Of course, in the scenario above you'd be more interest in timely outputs rather than output performance. 当然,在上述情况下,您会对及时输出而不是输出性能更感兴趣。

A simple approach to flush an output buffer in C++ us to use out << std::flush . 在C ++中刷新输出缓冲区的一种简单方法是使用out << std::flush If you quickly want to verify that this the problem you can set up the stream to flush after every output operation using out << std::unitbuf . 如果您想快速验证这一问题,则可以使用out << std::unitbuf将流设置为在每次输出操作后刷新。 There are a number of other approaches to automatically flush but these are a bit more involved. 有许多其他方法可以自动刷新,但是这些方法涉及更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM