How can a Java program get its own process ID?

后端 未结 22 2030
梦毁少年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:14

    I found a solution that may be a bit of an edge case and I didn't try it on other OS than Windows 10, but I think it's worth noticing.

    If you find yourself working with J2V8 and nodejs, you can run a simple javascript function returning you the pid of the java process.

    Here is an example:

    public static void main(String[] args) {
        NodeJS nodeJS = NodeJS.createNodeJS();
        int pid = nodeJS.getRuntime().executeIntegerScript("process.pid;\n");
        System.out.println(pid);
        nodeJS.release();
    }
    
    0 讨论(0)
  • 2020-11-22 04:15

    For completeness there is a wrapper in Spring Boot for the

    String jvmName = ManagementFactory.getRuntimeMXBean().getName();
    return jvmName.split("@")[0];
    

    solution. If an integer is required, then this can be summed up to the one-liner:

    int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
    

    If someone uses Spring boot already, she/he might use org.springframework.boot.ApplicationPid

    ApplicationPid pid = new ApplicationPid();
    pid.toString();
    

    The toString() method prints the pid or '???'.

    Caveats using the ManagementFactory are discussed in other answers already.

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

    Since Java 9 there is a method Process.getPid() which returns the native ID of a process:

    public abstract class Process {
    
        ...
    
        public long getPid();
    }
    

    To get the process ID of the current Java process one can use the ProcessHandle interface:

    System.out.println(ProcessHandle.current().pid());
    
    0 讨论(0)
  • 2020-11-22 04:17

    You can try getpid() in JNR-Posix.

    It has a Windows POSIX wrapper that calls getpid() off of libc.

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

    I know this is an old thread, but I wanted to call out that API for getting the PID (as well as other manipulation of the Java process at runtime) is being added to the Process class in JDK 9: http://openjdk.java.net/jeps/102

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

    For older JVM, in linux...

    private static String getPid() throws IOException {
        byte[] bo = new byte[256];
        InputStream is = new FileInputStream("/proc/self/stat");
        is.read(bo);
        for (int i = 0; i < bo.length; i++) {
            if ((bo[i] < '0') || (bo[i] > '9')) {
                return new String(bo, 0, i);
            }
        }
        return "-1";
    }
    
    0 讨论(0)
提交回复
热议问题