1

I wrote simple agent:

JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) {    
printf("Agent start");
}

And simple client:

public class Agent {
//java -agentpath:/path_to_lib Agent

public static void main(String[] args) throws InterruptedException {
    System.out.println("Main");
}}

And if I run program I will see the output below:

Main

Agent start

Why method main invoke before Agent_OnLoad?

VladoDemcak
  • 3,708
  • 3
  • 26
  • 38
  • 2
    Can you show how you are running it on command line? Also, add a new line to the printf in Agent_OnLoad so that the buffers get flushed. I wonder if that is causing the out-of-sequence outputs. You could also declare a static variable to indicate that the Agent_OnLoad has finished, and check it in Agent_OnUnload. – blackpen Oct 30 '16 at 19:13

1 Answers1

1

The Agent_OnLoad function is being called before main during start of the VM, however the stdout buffer is printing after reaching the newline. Add a \n at the end of printf to see it working. Following answer explains it in detail:

Why does printf not flush after the call unless a newline is in the format string?

Moreover, you can confirm this by putting a breakpoint on the printf (If you're using a debugger) to see that it'd be called at start but won't print until the buffer reaches newline character.

Community
  • 1
  • 1
Saqib Ahmed
  • 868
  • 15
  • 27