How can a Java program get its own process ID?

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

    Try Sigar . very extensive APIs. Apache 2 license.

    private Sigar sigar;
    
    public synchronized Sigar getSigar() {
        if (sigar == null) {
            sigar = new Sigar();
        }
        return sigar;
    }
    
    public synchronized void forceRelease() {
        if (sigar != null) {
            sigar.close();
            sigar = null;
        }
    }
    
    public long getPid() {
        return getSigar().getPid();
    }
    
    0 讨论(0)
  • 2020-11-22 04:29

    In Scala:

    import sys.process._
    val pid: Long = Seq("sh", "-c", "echo $PPID").!!.trim.toLong
    

    This should give you a workaround on Unix systems until Java 9 will be released. (I know, the question was about Java, but since there is no equivalent question for Scala, I wanted to leave this for Scala users who might stumble into the same question.)

    0 讨论(0)
  • 2020-11-22 04:30

    This is what I used when I had similar requirement. This determines the PID of the Java process correctly. Let your java code spawn a server on a pre-defined port number and then execute OS commands to find out the PID listening on the port. For Linux

    netstat -tupln | grep portNumber
    
    0 讨论(0)
  • 2020-11-22 04:31

    I am adding this, in addition to other solutions.

    with Java 10, to get process id

    final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    final long pid = runtime.getPid();
    out.println("Process ID is '" + pid);
    
    0 讨论(0)
  • 2020-11-22 04:32
    java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split("@")[0]
    
    0 讨论(0)
  • 2020-11-22 04:32

    The latest I have found is that there is a system property called sun.java.launcher.pid that is available at least on linux. My plan is to use that and if it is not found to use the JMX bean.

    0 讨论(0)
提交回复
热议问题