How can a Java program get its own process ID?

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

    There exists no platform-independent way that can be guaranteed to work in all jvm implementations. ManagementFactory.getRuntimeMXBean().getName() looks like the best (closest) solution, and typically includes the PID. It's short, and probably works in every implementation in wide use.

    On linux+windows it returns a value like 12345@hostname (12345 being the process id). Beware though that according to the docs, there are no guarantees about this value:

    Returns the name representing the running Java virtual machine. The returned name string can be any arbitrary string and a Java virtual machine implementation can choose to embed platform-specific useful information in the returned name string. Each running virtual machine could have a different name.

    In Java 9 the new process API can be used:

    long pid = ProcessHandle.current().pid();
    

提交回复
热议问题