Attach to current VM using com.sun.tools

huangapple go评论73阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年9月1日 05:09:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63678228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定