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

 

 

在以下系统测试通过:

1. windows 10

2. Red Hat Enterprise Linux Server release 6.4

3. CentOS Linux release 7.2.1511

猜你喜欢

转载自lixiaohui.iteye.com/blog/2324049