Java,获取Windows中当前运行进程的PID
这应该适用于Linux
、OSX
、Windows
和 HotSpot JVM。
import sun.management.VMManagement;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public static int getCurrentPID() {
try{
java.lang.management.RuntimeMXBean runtime =
java.lang.management.ManagementFactory.getRuntimeMXBean();
java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
sun.management.VMManagement mgmt =
(sun.management.VMManagement) jvm.get(runtime);
java.lang.reflect.Method pid_method =
mgmt.getClass().getDeclaredMethod("getProcessId");
pid_method.setAccessible(true);
return (Integer) pid_method.invoke(mgmt);
}
catch(Exception e){
e.printStackTrace();
System.out.println("Failed at getting the process ID");
System.exit(0);
}
}
像这样调用它:
System.out.println("PID: " + getCurrentPID());
对我来说,它会打印 processID:PID: 5728
资料来源:
Java 程序如何获得自己的进程 ID?
http://boxysystems.com/index.php/java-tip-find-process-id-of-running-java-process/