How can a Java program get its own process ID?

后端 未结 22 2036
梦毁少年i
梦毁少年i 2020-11-22 03:47

How do I get the id of my Java process?

I know there are several platform-dependent hacks, but I would prefer a more generic solution.

22条回答
  •  名媛妹妹
    2020-11-22 04:27

    Here's a backdoor method which might not work with all VMs but should work on both linux and windows (original example here):

    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);
    
    int pid = (Integer) pid_method.invoke(mgmt);
    

提交回复
热议问题