How a Java Application Can Discover its Process ID (PID)

from http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html

Occasionally it is important for an application to know its PID, specially if this application cooperates with other non-java applications.

Currently there is no direct support for retrieving an application's process id by using standard Java api (this might change in the future if RFEs like 42506224244896 or 4890847are resolved).

I found five ways how to get the PID from my Java code:

  1. Using the java management and monitoring API (java.lang.management):
    ManagementFactory.getRuntimeMXBean().getName();
    returns something like:
    28906@localhost
    where 28906 is the PID of JVM's process, which is in fact the PID of my app.

    This hack is JVM dependent and I tested it only with Sun's JVM.

    From Javadocs for getName() method of RuntimeMXBean:
    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.
    So even though this approach is the most comfortable one, your app can break if the implementation of this method changes.
  2. Using shell script in addition to Java properties Start your app with a shellscript like this:
    exec java -Dpid=$$ -jar /Applications/bsh-2.0b4.jar
    then in java code call:
    System.getProperty("pid");
  3. Using shell script's $! facility as described on this blog - this approach is fine if all you want is to create a pid file.
  4. Using Java Native Interface (JNI) - a very cumbersome and platform dependent solution.
  5. Using $PPID and Runtime.exec(String[]) method - described in detail in this post
    
    
    import java.io.IOException;
    
    public class Pid {
    public static void main(String[] args) throws IOException {
      byte[] bo = new byte[100];
      String[] cmd = {"bash", "-c", "echo $PPID"};
      Process p = Runtime.getRuntime().exec(cmd);
      p.getInputStream().read(bo);
      System.out.println(new String(bo));
    }
    }

It must be said that none of these approaches is perfect and each of them has some drawbacks.

posted @ 2016-03-30 17:20  princessd8251  阅读(204)  评论(0)    收藏  举报