是否可以在程序运行时获取其输出?
如果我有一个用 c++ 编写的 Windows 控制台程序,是否可以在程序运行时检索该程序的标准输出?如果没有,重写程序的最佳方法是什么?我知道我可以输出到文件并不断检查这些文件是否有更新。还有别的办法吗?有更好的办法吗?
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? 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
代码项目中有一些有趣的文章:
There are some interesting articles in Code Project:
是的,如果您自己启动该程序:
在 CreateProcess,您传递一个 STARTUPINFO ,您可以在其中可以指定 SDIN、STDOUT 和 STDERR 的句柄。请注意,一旦指定
STARTF_USESTDHANDLES
标志,oyu 就需要提供所有三个。另外,句柄必须是可继承的(否则子进程无法访问它们),因此 SECURITY_ATTRIBUTES 基本上至少需要如下所示:
您可以打开包含输入和接收输出的磁盘文件的句柄。或者,这可以是 管道在控制台应用程序运行时增量读取/写入。
Yes, if you start the program yourself:
in CreateProcess, you pass a STARTUPINFO where you can specify handles for SDIN, STDOUT and STDERR. Note that oyu need to supply all three once you specify the
STARTF_USESTDHANDLES
flag.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:
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.
如果它是现成的控制台可执行文件
您始终可以将其输出重定向到文件中,如下所示:
c:>回显一些文字>文件
或
c:>节目>文件
如果你的意思是这个?
因为你的问题不太清楚。
\\ 进入另一个程序
哦,好吧
不过我的第一个回答也已经习惯了。
因为还有另一种可能性,例如:
c:>节目1 | program2
它在控制台程序之间建立一个“管道”
程序2在其标准输入上接收程序1抛出到标准输出的内容
它在控制台程序中常见的老式 Unix 方式实践。
这样就不需要重写程序来专门支持它。
If it is a ready console executable
you can allways redirect it output in a file like this:
c:> echo Some text > file
or
c:> program > file
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 | program2
its make a "pipe" between console programs
program2 receive on it stdin what program1 throws to stdout
Its common old-aged Unix-way practice in console programs.
And in such way NO need to rewrite programs to specifically support it.
如果您只对程序的标准输出感兴趣,则 popen() 使这变得非常简单:
If you are only interested in the program's stdout, popen() makes this pretty simple:
您很可能需要使用管道来实现此目的,并且由于您使用的是 Windows,因此这里有一个指向 MSDN 文章,其中的示例似乎完全符合您的要求。
You'd most likely need to use pipes to achieve this, and since you're using Windows, here's a link to MSDN article with an example that seems to do exactly what you wanted.