Question

I am writing a program that uses JNI to interface with a simple c program. I have created the following programs:

public static void main(String[] args) {
    Hello h = new Hello();
    System.out.println("before");
    int number = h.sayHello();
    System.out.println(number);
    System.out.println("after");
}

and

JNIEXPORT int JNICALL Java_Hello_sayHello (JNIEnv *env, jobject obj) {
     printf("Hello JNI\n");
     return 10;
}

To my surprise this program returns:

before
10
after
Hello JNI

To me this is very strange because it is clear that the c program is executed between the "before" and "after" statement (The number 10 is printed). But why is the printf statement not executed when it is called. Is it somehow blocked by the jvm because only one program is allowed to write to the output at the same time? Is there a way to correct this behavior?

Was it helpful?

Solution

Yes. You will need to call flush.

In C, that is the fflush call -

printf("Hello JNI\n");
fflush(stdout);
return 10;

In Java, that is just flush on the Stream -

System.out.println("before");
System.out.flush();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top