如何找到在 java 中启动的进程的进程 ID (pid)? [英] How do I find the process ID (pid) of a process started in java?

查看:56
本文介绍了如何找到在 java 中启动的进程的进程 ID (pid)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我通过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?我在 The Official 中没有看到这样做的方法文档.我可以在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆