内部捕获/重定向标准输出?
这看起来有点像计算系统 101 问题,但我被难住了。
我正在将 C/C++ 项目 A 中的现有代码集成到我自己的项目 B 中。A 和 B 都将链接到单个可执行的线程进程中。项目 A 的代码大量使用 printf 进行输出。这很好,但我还想将该输出捕获到我自己的缓冲区中。有没有一种方法可以在 printf 调用写入后从 stdout 读取内容?我无法分叉进程或管道。我对 poll() stdout 或 dup() stdout 的努力没有成功(我可能在这里做错了什么)。
This seems like a bit of a computing systems 101 question, but I'm stumped.
I am integrating existing code from C/C++ project A into my own project B. Both A and B will be linked into a single executable, threaded process. Project A's code makes extensive use of printf for output. This is fine, but I want also to capture that output into my own buffers. Is there a way I can read from stdout once the printf calls have written to it? I cannot fork the process or pipe. And my efforts to poll() stdout, or to dup() it, have not succeeded (I may be doing something wrong here).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 freopen 更改描述符。
如果运行它,您将在 output.txt 中看到 printf 输出,并且屏幕上不会出现任何内容。
您现在可以打开文件来读取数据,甚至可以mmap 将其放入内存中空间并以这种方式处理它。
You can use freopen to change the descriptor.
If you run that you'll see the printf output in output.txt and nothing will go to your screen.
You can now open the file to read the data or you could even mmap it into your memory space and process it that way.
在 printf() 之前,您可以关闭 fd 1,并关闭 dup2() 您在 fd 1 中创建的管道。
Before you printf(), you could close fd 1, and dup2() a pipe that you've created into fd 1.
更不用说:现在有一个方便的 U-Streams C 源代码库,可以使重定向 stdout 和 stderr 变得非常简单。您甚至可以轻松地将它们重定向到多个目的地。而且,您还可以创建自己的流,并且可以以与 stdout 和 stderr 行为完全相同的方式使用流。
寻找 U-Streams C 库...确实很方便。
Not to mention: there is now a handy U-Streams C source code library that makes redirecting stdout and stderr quite trivial. And you can even redirect them very easily to multiple destinations. And, you can create your own streams besides that can be used in exactly the same way stdout and stderr behave.
Look for the U-Streams C Library... handy indeed.
一旦出去了,就没有了。如果您想将其全部编译为单个可执行文件,则必须通过搜索和替换来遍历 A 的代码,并将所有这些
printf
调用更改为对您自己的流的调用,您可以在其中可以复制它们然后将它们传递到标准输出。Once it's gone out, it's gone. If you want to compile it all into a single executable, you'll have to go through the code for A with a search and replace and change all those
printf
calls into ones to your own stream, where you can copy them and then pass them on to stdout.