How can a Java program get its own process ID?

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

    It depends on where you are looking for the information from.

    If you are looking for the information from the console you can use the jps command. The command gives output similar to the Unix ps command and comes with the JDK since I believe 1.5

    If you are looking from the process the RuntimeMXBean (as said by Wouter Coekaerts) is probably your best choice. The output from getName() on Windows using Sun JDK 1.6 u7 is in the form [PROCESS_ID]@[MACHINE_NAME]. You could however try to execute jps and parse the result from that:

    String jps = [JDK HOME] + "\\bin\\jps.exe";
    Process p = Runtime.getRuntime().exec(jps);
    

    If run with no options the output should be the process id followed by the name.

提交回复
热议问题