如何监控ProcessBuilder运行的外部进程? [英] How to monitor external process ran by ProcessBuilder?

查看:223
本文介绍了如何监控ProcessBuilder运行的外部进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该相当简单,但我没有看到任何有用的 JavaDocs

This should be rather simple, but I don't see anything helpful in JavaDocs.

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

What I need is to run some external process from my Java code and then be able to monitor if this process has been shutdown or not. In other words, I want to be able to reliably determine whether or not my external process was not ended by user.

如果不存在跨平台解决方案,我会接受任何在Linux下工作。

If no cross platform solution exists, I will accept anything working under 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();
    }
}


推荐答案

开始一个新的Thread调用 Process.waitFor()并在该调用返回时设置一个标志。然后,你可以在想要查看进程是否已经完成时检查该标志。

Start a new Thread which calls Process.waitFor() and sets a flag when that call returns. then, you can check that flag whenever you want to see if the process has completed.

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;
  }
}

(省略了一些样板)。

这篇关于如何监控ProcessBuilder运行的外部进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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