Java 获取当前JVM进程ID

阅读更多

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):

 
Java 获取当前JVM进程ID_第1张图片
 

 

在以下系统测试通过:

1. windows 10

2. Red Hat Enterprise Linux Server release 6.4

3. CentOS Linux release 7.2.1511

  • Java 获取当前JVM进程ID_第2张图片
  • 大小: 26.4 KB
  • 查看图片附件

你可能感兴趣的:(java,pid,jvm)