How to get the PID of the current JVM
At work, I needed to get the PID of the current JVM to be able to pass it to another JVM, which then would shut it down. After some googling and a bunch of failed attempts I ended up with this:
private int getProcessId() {
String name = ManagementFactory.getRuntimeMXBean().getName();
StringBuffer pid = new StringBuffer();
for (int i = 0, l = name.length(); i < l; i++) {
if (Character.isDigit(name.charAt(i))) {
pid.append(name.charAt(i));
} else if (pid.length() > 0) {
break;
}
}
try {
return Integer.parseInt(pid.toString());
} catch (NumberFormatException e) {
return 0;
}
}
The RuntimeMXBean is available from Java 5 and allows you to fetch the name of the running JVM. Unfortunately its output isn't specified in the documentation, but Sun's JVM seems to return the following processId@machineId (e.g., 5575@blanco-local) on both Windows, Linux and OS X. This output, we can simply parse to get hold of a PID and that's what's being done in the sample code above.
Post your own comment
Pages linking to this entry
Pingback is enabled on all archived entries. Read more about pingback in the Pingback 1.0 Specification.
No pingbacks.
