简体   繁体   English

是否可以在程序运行时获得程序的输出?

[英]Is it possible to get the output of a program while it's running?

If I have a windows console program written with c++, is it possible to retrieve that program's standard output, while the program is running? 如果我有一个用c ++编写的Windows控制台程序,是否可以在程序运行时检索该程序的标准输出? And if not, what would be the best way to rewrite the program? 如果没有,那么重写程序的最佳方法是什么? I know I could output to files and continuously check those files for updates. 我知道我可以输出到文件并不断检查这些文件的更新。 Is there another way? 还有另外一种方法吗? Is there a better way? 有没有更好的办法?

There are some interesting articles in Code Project: Code Project中有一些有趣的文章:

If it is a ready console executable you can allways redirect it output in a file like this: 如果它是一个现成的控制台可执行文件,你可以继续将它的输出重定向到这样的文件中:

c:> echo Some text > file c:> echo一些文本>文件

or 要么

c:> program > file c:>程序>文件

If you mean this? 如果你的意思是这个? As your question is not exactly clear. 由于你的问题不是很清楚。

\\\\ into another program 进入另一个程序

Oh, Ok 哦好的
But my first answer is also used to it. 但我的第一个答案也习惯了。 As there is also another possibility like: 因为还有另一种可能性:

c:> program1 | c:> program1 | program2 程序2

its make a "pipe" between console programs 它在控制台程序之间形成一个“管道”
program2 receive on it stdin what program1 throws to stdout program2接收stdin什么program1抛出到stdout
Its common old-aged Unix-way practice in console programs. 它在控制台程序中常见的老式Unix方式练习。
And in such way NO need to rewrite programs to specifically support it. 并且以这种方式,不需要重写程序来专门支持它。

Yes, if you start the program yourself: 是的,如果您自己启动该程序:

in CreateProcess , you pass a STARTUPINFO where you can specify handles for SDIN, STDOUT and STDERR. CreateProcess中 ,您传递一个STARTUPINFO ,您可以在其中指定SDIN,STDOUT和STDERR的句柄。 Note that oyu need to supply all three once you specify the STARTF_USESTDHANDLES flag. 请注意,一旦指定了STARTF_USESTDHANDLES标志, STARTF_USESTDHANDLES就需要提供所有三个标志。

Also, the handles need to be inheritable (otherwise, the child process can't access them), so the SECURITY_ATTRIBUTES basically need to look at least like this: 此外,句柄需要是可继承的(否则,子进程无法访问它们),因此SECURITY_ATTRIBUTES基本上至少需要看起来像这样:

SECURITY_ATTRIBUTES secattr = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };

You could open handles to disk files that contain input and receive output. 您可以打开包含输入和接收输出的磁盘文件的句柄。 Alternatively, this can be Pipes that can be read / written incrementally while the console app is running. 或者,这可以是在控制台应用程序运行时可以逐步读取/写入的管道

If you are only interested in the program's stdout, popen() makes this pretty simple: 如果你只对程序的stdout感兴趣,popen()会让这很简单:

FILE* program_output = popen("command line to start the other program");
//read from program_output as you would read a "normal" file
//...
pclose(program_output);

您很可能需要使用管道来实现这一目标,并且由于您使用的是Windows,因此这里有一个指向MSDN文章的链接,其示例似乎完全符合您的要求。

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

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