How can a Java program get its own process ID?

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

提交回复
热议问题