I am invoking a C library via JNI that prints to stdout. How can I redirect this output to System.out?
2 Answers
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.
1 Comment
System.out variable in the JVM and call native C code, the output of the C method will still be written to the terminal while your java output may be directed elsewhere. If you know a workaround for this, please let me know.