How do I obtain the PID of a spawned java process
Question
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.
Solution
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]);
}
}
}
OTHER TIPS
you can try execute command
pidof <program name>
for you to find the pid of your program.
It is in Linux env.
Note that Java 9 is going to expose some system-agnostic methods such as:
System.out.println("Your pid is " + Process.getCurrentPid());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow