Java getPid()
Ever since I started programming in Java it has bugged me that I can't get the process id of the Java VM. Well today I was browsing the OpenJPA code and found this gem:
private static String getPid() {
// This relies on the undocumented convention of the
// RuntimeMXBean's name starting with the PID, but
// there appears to be no other way to obtain the
// current process' id, which we need for the attach
// process
RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
String pid = bean.getName();
if (pid.indexOf("@") != -1) {
pid = pid.substring(0, pid.indexOf("@"));
}
return pid;
}

4 Comments:
This is cool. Since its an undocumented convention, I wonder if it works the same on different vendor JVM's
I needed to be able to create symbolic links from within a Java process on a project earlier this year and found an academic research codebase written in C using JNI somewhere out there and beat the hell out of it to get it to work. Now I can't find a link to it. You can't really rely on System.getRuntime().exec() because it does a complete process fork making a copy of the entire Java heap to do the exec. (Why the JVM team doesn't use tfork is still a mystery)
k singh, it may work on IBM since IBM tries very hard to support Sun conventions so porting work is a minimum. Also, this code came from OpenJPA which is embedded in to the next version of Websphere. It may work on Jroket since it seems to use the Sun class library, and I doubt it works on Harmony.
nick, ant has an optional symlink task. You should be able to either use the ant jar directly or grab a source.
Looking at the doc, I'm pretty sure the Ant implementation does a System.getRuntime().exec(), which doesn't scale.
Post a Comment
<< Home