如何监控ProcessBuilder运行的外部进程?

时间:2012-07-16 18:35:15

标签: java multithreading process

这应该很简单,但我在JavaDocs中看不到任何有用的东西。

我需要的是从我的Java代码运行一些外部进程,然后能够监视此进程是否已关闭。换句话说,我希望能够可靠地确定我的外部流程是否未被用户终止。

如果不存在跨平台解决方案,我将接受在Linux下工作的所有内容。

我目前的代码片段:

public static void main(String[] args) {
    ProcessBuilder pb = new ProcessBuilder("some proces name");

    try {
        Process p = pb.start();
        // p.isRunning(); <- now, that would be helpful :-)
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3 个答案:

答案 0 :(得分:7)

启动一个调用Process.waitFor()的新线程,并在该调用返回时设置一个标志。然后,只要您想查看该过程是否已完成,就可以检查该标志。

public class ProcMon implements Runnable {

  private final Process _proc;
  private volatile boolean _complete;

  public boolean isComplete() { return _complete; }

  public void run() {
    _proc.waitFor();
    _complete = true;
  }

  public static ProcMon create(Process proc) {
    ProcMon procMon = new ProcMon(proc);
    Thread t = new Thread(procMon);
    t.start();
    return procMon;
  }
}

(省略了一些样板)。

答案 1 :(得分:5)

我不确定我是否理解这个问题,但实现此目的的一种方法是致电process.exitValue();。如果进程尚未终止,它会抛出异常:

/**
 * Returns the exit value for the subprocess.
 *
 * @return  the exit value of the subprocess represented by this 
 *          <code>Process</code> object. by convention, the value 
 *          <code>0</code> indicates normal termination.
 * @exception  IllegalThreadStateException  if the subprocess represented 
 *             by this <code>Process</code> object has not yet terminated.
 */
abstract public int exitValue();

如果您不介意破解,如果您正在使用UNIXProcess类的~Unix系统,则可以执行以下操作。但这确实使用了反射:

ProcessBuilder pb = new ProcessBuilder("/bin/sleep", "5");
Process process = pb.start();
// open accessability of the UNIXProcess.hasExited field using reflection
Field field = process.getClass().getDeclaredField("hasExited");
field.setAccessible(true);
// now we can get the field using reflection
while (!(Boolean) field.get(process)) {
    ...
}

答案 2 :(得分:1)

根据问题的具体代码段,我可能会有用,因为1.8 Process类有一个isAlive()方法可用

文档链接:https://docs.oracle.com/javase/8/docs/api/java/lang/Process.html

祝所有读这篇文章的人好运!