如何使用 JNI 将终端输出从 C 程序重定向到 System.out?
我正在通过 JNI 调用一个 C 库,该库打印到标准输出。 如何将此输出重定向到 System.out?
I am invoking a C library via JNI that prints to stdout. How can I redirect this output to System.out?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
System.out
是stdout
。 您是否遇到了一些更根本的问题(也许是混合输出?)。由于另一位成员也提到了最后一点 - 我应该进一步解释:
System.out
和stdout
都对应于文件描述符 #1。然而,Java 的
OutputStream
(及其派生类)和 C 的stdio
库都有自己的(独立)缓冲机制,以减少对底层write 的调用次数系统调用。 仅仅因为您调用了
printf
或类似函数,并不能保证您的输出会立即出现。由于这些缓冲方法是独立的,因此 Java 代码内部的输出(理论上)可能会混淆,或者相对于 C 代码的输出出现乱序。
如果这是一个问题,您应该安排在调用 JNI 函数之前以及在 C 函数中调用
System.out.flush()
(如果它使用stdio
而不是低级write
调用),您应该在返回之前调用fflush(stdout)
。System.out
isstdout
. Is there some more fundamental problem you're having (mixed up output, perhaps?).Since another member has also mentioned that last point - I should explain further:
System.out
andstdout
both correspond to file descriptor #1.However both Java's
OutputStream
(and derived classes) and C'sstdio
library have their own (independent) buffering mechanisms so as to reduce the number of calls to the underlyingwrite
system call. Just because you've calledprintf
or similar, it's not guaranteed that your output will appear straightaway.Because these buffering methods are independent, output from within Java code could (in theory) get mixed up or otherwise appear out-of-order relative to output from the C code.
If that's a concern, you should arrange to call
System.out.flush()
before calling your JNI function, and in your C function (if it's usingstdio
rather than the low-levelwrite
call) you should callfflush(stdout)
before returning.正如 Alnitak 所写,您应该打印到标准输出。 您应该注意,该消息可能需要一段时间才会显示在屏幕上。 如果时间很重要,您应该在打印到标准输出时打印带有消息的时间戳。
As Alnitak wrote, you should print to stdout. You should note that it can take a while for the message to appear on the screen. In case the timing is important, you should print a timestamp with the message when you print to stdout.