If I get a process object in Java through Runtime.getRuntime().exec(...)
, or ProcessBuilder.start()
, I can wait for it through Process.waitFor()
, which is like Thread.join()
, or I could kill it with Process.destroy()
, which is like the deprecated Thread.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?
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