How can a Java program get its own process ID?

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

    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";
    }
    

提交回复
热议问题