How do I find the process ID (pid) of a process started in java?
Solution 1
This guy calls out to bash to get the PID. I'm not sure if there is an java solution to the problem.
/**
* Gets a string representing the pid of this program - Java VM
*/
public static String getPid() throws IOException,InterruptedException {
Vector<String> commands=new Vector<String>();
commands.add("/bin/bash");
commands.add("-c");
commands.add("echo $PPID");
ProcessBuilder pb=new ProcessBuilder(commands);
Process pr=pb.start();
pr.waitFor();
if (pr.exitValue()==0) {
BufferedReader outReader=new BufferedReader(new InputStreamReader(pr.getInputStream()));
return outReader.readLine().trim();
} else {
System.out.println("Error while getting PID");
return "";
}
}
Source: http://www.coderanch.com/t/109334/Linux-UNIX/UNIX-process-ID-java-program
Solution 2
Similar to the other tools mentioned, there is the jps
command line tool that comes with the Java runtime. It spits out the PIDs of all running JVMs. The benefit is the output one needs to parse is confined to only the JVM processes.
Leo Izen
Who am I? Leo Izen. Thebombzen. Sedna. A nerd. Mayep S Photochop.
Updated on July 09, 2022Comments
-
Leo Izen almost 2 years
If I get a process object in Java through
Runtime.getRuntime().exec(...)
, orProcessBuilder.start()
, I can wait for it throughProcess.waitFor()
, which is likeThread.join()
, or I could kill it withProcess.destroy()
, which is like the deprecatedThread.stop()
.BUT: How do I find the pid of the Process Object? I don't see a method for doing that in The Official Documentation. Can I do this in Java? If so, how?
-
Mike Baranczak about 13 yearsAnother benefit: it's cross-platform, unlike tasklist.
-
Leo Izen about 13 yearsYou are assuming I'm on Windows, which I'm not.
-
splashout almost 8 yearsI think this will give the pid of the JVM process... not the process spawned by Java which I believe is what the question is asking.
-
nsfyn55 almost 8 yearsI think you need to read a bit closer. It spawns a process thats only job is to echo its own PID to its stdout which itself is piping to the stdin file descriptor associated with the JVM.
-
user924272 almost 7 yearsVectors are old-hat, and is synchronized - no real need to use that type of collection - try using an ArrayList instead. Just saying.
-
nsfyn55 almost 7 yearsJust saying what? This is not germane to the problem. The question is about accessing a
PID
not java best practices.