如何找到在java中启动的进程的进程ID(pid)? [英] How do I find the process ID (pid) of a process started in java?
问题描述
如果我通过 Runtime.getRuntime()。exec(...)
或 ProcessBuilder.start()获取Java中的流程对象
,我可以通过 Process.waitFor()
等待它,就像 Thread.join()
,或者我可以用 Process.destroy()
杀死它,这就像弃用的 Thread.stop()
。
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()
.
但是:我如何找到过程对象的pid?我没有在官方看到这样做的方法文档。我可以用Java做到这一点吗?如果是这样,怎么样?
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?
推荐答案
这家伙呼唤bash获取PID。我不确定是否有解决问题的java解决方案。
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 "";
}
}
资料来源:
http://www.coderanch.com/t/109334/Linux-UNIX/UNIX-process -ID-java-program
这篇关于如何找到在java中启动的进程的进程ID(pid)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!