问题
A similar question has already been answered for Windows, but I could not find out how to achieve the same on Linux.
I want to deepen my knowledge in JNI. I already got JNI projects working with JNI_CreateJavaVM, creating a new JVM from within the native application.
But this time I would like to not create the JVM within the native application (i.e., not using JNI_CreateJavaVM), but to attach to an already running one (i.e., using AttachCurrentThread on a VM that has been started before the native application by some java myApplication call).
Is there a way on Linux how to achieve this? I need to get a JavaVM object of the running JVM. I tried to use JNI_GetCreatedJavaVMs, but this does not return any JVMs (I think this method only returns VMs created by the current process, e.g., by using JNI_CreateJavaVM, and not all VMs that are running on the system)
回答1:
JNI functions can be used only within the process that started JVM. JNI does not allow you to control other processes.
However, there is a way to load your code in the context of different JVM process using HotSpot Dynamic Attach API.
- Compile your code into an agent library (.so);
- Create Agent_OnAttach function that will be an entry point for your code;
- Load the agent library using Dynamic Attach.
There is Java API to attach to remote JVM and to load agent library in its context. But you can also do it from native code like in my jattach project.
回答2:
If i understand correctly, you want to make calls from one OS process (your native application) to a separate OS process (running a java application). You can't make "direct" calls to a JVM in another process. You need to use some sort of remote protocol. Two "builtin" options are JMX (via RMI) or straight RMI. Alternately, you could expose a webservice on the other JVM and invoke it using standard HTTP interactions.
来源:https://stackoverflow.com/questions/38588632/attach-native-application-via-jni-to-already-running-jvm-on-linux