mafioso mafioso - 1 month ago 10
C Question

JNI method executes after terminating application

I have a

public native static void printSpielerToFile(Spieler s[], int length);
method in Java.

I call it that way in java:

public static void setMeineSpieler(ArrayList<Spieler> meineSpieler) {
JNIResultSet.meineSpieler = meineSpieler;
// size -1 because the last object is empty due to the empty row on the bottom
Spieler[] s = new Spieler[meineSpieler.size() - 1];

for (int i = 0; i < meineSpieler.size() - 1; i++) {
s[i] = meineSpieler.get(i);
}
printSpielerToFile(s, s.length);
}


and the C code looks like that:

JNIEXPORT void JNICALL
Java_model_JNIResultSet_printSpielerToFile(JNIEnv *env, jclass jcl, jobjectArray arr, jint len) {
int i = 0;
printf("length: %d", len);
}


Everything works fine in java but the problem is that the C code only then executes if the application finished.

I start the application in linux by a script and if I terminate it, the method executes.

That looks like that:

enter image description here

So my question is: Why does this method execute after termination and not immediately after calling it in java?

Answer

Why does this method execute after termination and not immediately after calling it in java?

It doesn't. That's when its output appears on the console, but the method executed earlier.

The standard output is buffered, and you never explicitly flush or close it, and not enough is written to it to fill the buffer during one run of the program, so no output appears until stdout is closed at program termination. Add

fflush(stdout);

to your native method, after the printf(), to cause the output to appear on the console as soon as it is printed.

Comments