How do I redirect terminal output from a C program to System.out with JNI?

血红的双手。 提交于 2019-12-10 17:57:20

问题


I am invoking a C library via JNI that prints to stdout. How can I redirect this output to System.out?


回答1:


System.out is stdout. 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 and stdout both correspond to file descriptor #1.

However both Java's OutputStream (and derived classes) and C's stdio library have their own (independent) buffering mechanisms so as to reduce the number of calls to the underlying write system call. Just because you've called printf 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 using stdio rather than the low-level write call) you should call fflush(stdout) before returning.




回答2:


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.



来源:https://stackoverflow.com/questions/290743/how-do-i-redirect-terminal-output-from-a-c-program-to-system-out-with-jni

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!