How can a Java program get its own process ID?

后端 未结 22 2039
梦毁少年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:19
    public static long getPID() {
        String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
        if (processName != null && processName.length() > 0) {
            try {
                return Long.parseLong(processName.split("@")[0]);
            }
            catch (Exception e) {
                return 0;
            }
        }
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 04:20

    The following method tries to extract the PID from java.lang.management.ManagementFactory:

    private static String getProcessId(final String fallback) {
        // Note: may fail in some JVM implementations
        // therefore fallback has to be provided
    
        // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
        final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
        final int index = jvmName.indexOf('@');
    
        if (index < 1) {
            // part before '@' empty (index = 0) / '@' not found (index = -1)
            return fallback;
        }
    
        try {
            return Long.toString(Long.parseLong(jvmName.substring(0, index)));
        } catch (NumberFormatException e) {
            // ignore
        }
        return fallback;
    }
    

    Just call getProcessId("<PID>"), for instance.

    0 讨论(0)
  • 2020-11-22 04:20

    Based on Ashwin Jayaprakash's answer (+1) about the Apache 2.0 licensed SIGAR, here is how I use it to get only the PID of the current process:

    import org.hyperic.sigar.Sigar;
    
    Sigar sigar = new Sigar();
    long pid = sigar.getPid();
    sigar.close();
    

    Even though it does not work on all platforms, it does work on Linux, Windows, OS X and various Unix platforms as listed here.

    0 讨论(0)
  • 2020-11-22 04:23

    You could use JNA. Unfortunately there is no common JNA API to get the current process ID yet, but each platform is pretty simple:

    Windows

    Make sure you have jna-platform.jar then:

    int pid = Kernel32.INSTANCE.GetCurrentProcessId();
    

    Unix

    Declare:

    private interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);   
        int getpid ();
    }
    

    Then:

    int pid = CLibrary.INSTANCE.getpid();
    

    Java 9

    Under Java 9 the new process API can be used to get the current process ID. First you grab a handle to the current process, then query the PID:

    long pid = ProcessHandle.current().pid();
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 04:28

    You can check out my project: JavaSysMon on GitHub. It provides process id and a bunch of other stuff (CPU usage, memory usage) cross-platform (presently Windows, Mac OSX, Linux and Solaris)

    0 讨论(0)
提交回复
热议问题