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


转自:http://www.blogjava.net/temper/archive/2010/07/01/324992.html


Occasionally it is important for an application to know its PID,specially if this application cooperates with other non-javaapplications. Currently there is no direct support for retrieving anapplication's process id by using standard Java api (this might changein the future if RFEs like 42506224244896 or 4890847 are 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 virtualmachine. The returned name string can be any arbitrary string and aJava virtual machine implementation can choose to embedplatform-specific useful information in the returned name string. Eachrunning 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 propertiesStart 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.

I know that one of Sun's main priorities for Java is cross-platformcompatibility, but I have to agree with the comments on the RFEs abovewhich support the addition of a getPid() method to JDK. I especiallylike this one:
Come on Sun, this started 4.5 years ago. Give us the
PID. We need it. We want it. We demand it.
And another thing ... you will save a lot of developers a
lot of time currently spent searching through the
documentation trying to find a getPID method that isn't
there!


没有一个平台独立的方法能够在所有的JVM上实现。一个最简单、最接近取得PID的办法是使用:

ManagementFactory.getRuntimeMXBean().getName() 。

取得到的字符窜的格式为[PROCESS_ID]@[MACHINE_NAME],通过解析这个字符串就可以得到java进程的PID。

在以下平台上测试通过:

1、Windows、Linux上的Sun JDK1.5、JDK6

2、HP-UX上的JDK1.5、JDK6

3、Linux上的JRockit  R27.6


private int getPid()
    {
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
        String name = runtime.getName(); // format: "pid@hostname"
        try
        {
            return Integer.parseInt(name.substring(0, name.indexOf('@')));
        }
        catch (Exception e)
        {
            return -1;
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值