How can a Java program get its own process ID?

后端 未结 22 2298
梦毁少年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: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();
    

提交回复
热议问题