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 4250622, 4244896 or 4890847are resolved).
I found five ways how to get the PID from my Java code:
- Using the java management and monitoring API (java.lang.management):
ManagementFactory.getRuntimeMXBean().getName();returns something like:28906@localhostwhere 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. - Using shell script in addition to Java properties Start your app with a shellscript like this:
exec java -Dpid=$$ -jar /Applications/bsh-2.0b4.jarthen in java code call:System.getProperty("pid"); - Using shell script's $! facility as described on this blog - this approach is fine if all you want is to create a pid file.
- Using Java Native Interface (JNI) - a very cumbersome and platform dependent solution.
- Using
$PPIDandRuntime.exec(String[])method - described in detail in this postimport 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.
小小菜鸟一枚
浙公网安备 33010602011771号