英文:
Attach to current VM using com.sun.tools
问题
可以获取程序当前运行的虚拟机吗?我知道有一个VirtualMachine.list()
方法,但我无法弄清楚如何找到正确的虚拟机。我不能根据特定的displayName
进行搜索,因为它是动态的。有没有其他方法可以找到正确的虚拟机?
英文:
Is it possible to get the VM the program is currently running in? I know there is a VirtualMachine.list()
method but I can't figure out how to find the right one. I can't search for a specific displayName
since it's dynamic.
Is there another way to find the right VM?
答案1
得分: 3
要附加到的虚拟机(VM)的 ID 是进程 ID(pid)。因此,您只需查找当前 JVM 进程的 pid。
以下是一种实现方法:
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
String jvmPid = jvmName.substring(0, jvmName.indexOf('@'));
VirtualMachine self = VirtualMachine.attach(jvmPid);
注意:自 JDK 9 起,附加到当前进程需要设置系统属性:
-Djdk.attach.allowAttachSelf=true
英文:
The ID of the VM to attach to is a process ID (pid). So, you just need to find pid of the current JVM process.
Here is a way to do this:
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
String jvmPid = jvmName.substring(0, jvmName.indexOf('@'));
VirtualMachine self = VirtualMachine.attach(jvmPid);
Note: since JDK 9 attaching to current process requires setting the system property:
-Djdk.attach.allowAttachSelf=true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论