Java 获取当前JVM进程ID
程序员文章站
2022-05-26 10:31:55
...
Java 获取当前JVM进程ID
public static final int jvmPid() { try { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); Field jvm = runtime.getClass().getDeclaredField("jvm"); jvm.setAccessible(true); VMManagement mgmt = (VMManagement) jvm.get(runtime); Method pidMethod = mgmt.getClass().getDeclaredMethod("getProcessId"); pidMethod.setAccessible(true); int pid = (Integer) pidMethod.invoke(mgmt); return pid; } catch (Exception e) { return -1; } }
tips:可以用jps命令查看jvm进程及其ID,如(Red Hat Enterprise Linux Server release 6.4):
在以下系统测试通过:
1. windows 10
2. Red Hat Enterprise Linux Server release 6.4
3. CentOS Linux release 7.2.1511