How can a Java program get its own process ID?

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

    Based on Ashwin Jayaprakash's answer (+1) about the Apache 2.0 licensed SIGAR, here is how I use it to get only the PID of the current process:

    import org.hyperic.sigar.Sigar;
    
    Sigar sigar = new Sigar();
    long pid = sigar.getPid();
    sigar.close();
    

    Even though it does not work on all platforms, it does work on Linux, Windows, OS X and various Unix platforms as listed here.

提交回复
热议问题