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.
Asked
Active
Viewed 3,819 times
2
-
1This [link](http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html) may help you. – Prince John Wesley Oct 20 '11 at 10:11
-
3Appears to be a question very similar to [Process ID in Java](http://stackoverflow.com/questions/35842/process-id-in-java) – Ben van Gompel Oct 20 '11 at 10:12
-
3Ken a little bit more information may be helpful. It sounds like you are wanting to launch Java program A, program B, and program C. Then have Java program D kill the processes of A,B, and C. Are you launching A,B, and C from program D? Is there a reason A,B, and D can't tidy up after themselves? – Kevin D Oct 20 '11 at 10:14
-
If you don't tell us *how* you are creating these processes, we can't help you. – bmargulies Oct 20 '11 at 10:23
-
hey yes, basically i am using jvm A to spawn a seperate process of jvm B and jvm A would have ended. after doing some work, I will need jvm C to kill off jvm B – ken Oct 20 '11 at 10:25
-
I tried using java native but to no avail – ken Oct 20 '11 at 10:27
3 Answers
6
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]);
}
}
}

Narendra Yadala
- 9,554
- 1
- 28
- 43
-
Works on Win7 64 bits and JDK 1.8 :D I just changed: if (javaProcess.length > 1 && javaProcess[1].contains("myJarName")) – Broken_Window Mar 04 '15 at 17:18
0
Note that Java 9 is going to expose some system-agnostic methods such as:
System.out.println("Your pid is " + Process.getCurrentPid());

Dici
- 25,226
- 7
- 41
- 82
0
you can try execute command
pidof <program name>
for you to find the pid of your program.
It is in Linux env.

TheOneTeam
- 25,806
- 45
- 116
- 158