I am writing several java programs and will need to kill off/clean up in a seperate JVM after I am done with whatever I wanted to do. For this, I will need to get the PID of the java process which I am creating.
jps -l
works both on Windows and Unix. You can invoke this command from your java program using Runtime.getRuntime().exec
. Sample output of jps -l
is as follows
9412 foo.bar.ClassName
9300 sun.tools.jps.Jps
You might need to parse this and then check for the fully qualified name and then get the pid from the corresponding line.
private static void executeJps() throws IOException {
Process p = Runtime.getRuntime().exec("jps -l");
String line = null;
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream(), "UTF-8"));
while ((line = in.readLine()) != null) {
String [] javaProcess = line.split(" ");
if (javaProcess.length > 1 && javaProcess[1].endsWith("ClassName")) {
System.out.println("pid => " + javaProcess[0]);
System.out.println("Fully Qualified Class Name => " +
javaProcess[1]);
}
}
}