How to find the pid of a java process from code
This blog has been quiet for a while, that’s about to change, but in the meantime I came across a very interesting way to get hold of the PID for your running java process from code, which I thought I’d put up straight away.
This makes use of the Management JMX beans to find the information, but the good news is that it seems you don’t have to do anything special, such as add VM system properties, to make it work.
Not sure this will work on every OS/vm, but on the ones I have tried there’s no problem.
Seems to work on both Windows on Linux
For me, the below produces:
ProcessName=[1136@iblongsw253311]
PID=[1136]
try {
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
String s = mx.getName();
System.out.println("ProcessName=["+s+"]");
String[] pidAndHost = s.split("@");
if ( pidAndHost.length == 2) {
int pid = Integer.valueOf(pidAndHost[0]);
System.out.println("PID=[" + pid + "]");
}
}
catch( Exception e) {
System.out.println("Whoops, can't find a PID");
}
}
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply