使用 NDK 捕获 stdout/stderr
我正在移植一些现有的 C 代码以在 Android 上运行。此 C 代码将大量输出写入 stdout/stderr。我需要在内存缓冲区或文件中捕获此输出,以便我可以通过电子邮件发送或以其他方式共享它。
理想情况下,我怎样才能实现这一目标而不修改现有的 C 代码?
注意:这个问题与将输出重定向到 adb 或 logcat 无关;我需要在设备上本地缓冲输出。我知道以下问题似乎无法解决我的查询:
I am porting some existing C code to run on Android. This C code writes lots of output to stdout/stderr. I need to capture this output, either in a memory buffer or a file, so I can then send it by email or otherwise share it.
How can I achieve this, ideally without modifying the existing C code?
Note: this question is NOT about redirecting the output to adb or logcat; I need to buffer the output locally on the device. I am aware of the following questions, which do not appear to address my query:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用类似的方法将 stderr 重定向到管道。让管道另一端的读取器写入 logcat:
您将希望在其自己的线程中运行它。我在 Java 中启动线程,然后让 Java 线程调用此 NDK 代码,如下所示:
Use something like this to redirect stderr to a pipe. Have a reader on the other side of the pipe write to logcat:
You'll want to run this in its own thread. I spin up the thread in Java and then have the Java thread call this NDK code like this:
stdout 是路径 1,stderr 是路径 2。了解了这一点,您可以建立想要作为输出目标的新路径,然后将它们强制到 stdout 和/或 stderr。 实际示例使用 dup 或 dup2 中有一个示例展示了如何执行此操作。
stdout is path 1 and stderr is path 2. Knowing this, you can establish new path(s) that you want to be the output destination, then coerce them into stdout and/or stderr. There's an example showing how to do this at practical examples use dup or dup2.
我使用了詹姆斯·摩尔提交的答案,但我希望能够打开和关闭日志记录。这样我可以将 mKeepRunning 设置为 false,它将关闭。我还需要将 O_NONBLOCK 标志添加到文件中,以便它不再是阻塞调用。
I used the answer submitted by James Moore, but I wanted to be able to turn the logging on and off. With this I can set the mKeepRunning to false and it will shut down. I also needed to add the O_NONBLOCK flag to the file so it was no longer a blocking call.