【问题标题】:How to come out of getRuntime.exec() when the executed process takes a long time to execute?getRuntime.exec() 被执行的进程执行时间长,如何退出?
【发布时间】:2014-04-17 00:33:48
【问题描述】:

在 Java 程序中我正在运行以下内容?

Process p = Runtime.getRuntime().exec("java -cp - src\ MyCode");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream));

MyCode 程序是一个 java 程序。

现在,MyCode 可以进入像 infinite looplong execution cycle 这样的情况。目前,在这种情况下,进程 p 正在“永远”等待 MyCode。我需要的是,每当 MyCode 执行超过一定时间时,我希望进程 p 结束或被销毁,以便我可以继续主程序中的下一行。

感谢任何帮助!

【问题讨论】:

标签: java command-line process


【解决方案1】:

Apache commons exec 包含一个 ExecuteWatchdog 类 https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/ExecuteWatchdog.html

ExecuteWatchdog watchdog = new ExecuteWatchdog(30000);
Executer exec = new Executer(myloghandler, watchdog);
exec.setCommandLine(mycmdline);
int exitvalue = exec.execute();
if (Execute.isFailure(exitvalue) && watchdog.killedProcess()) {
    // it was killed on purpose by the watchdog
}

【讨论】:

    【解决方案2】:

    我建议你使用ScheduledExecutorService:

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
    

    然后就可以定义 StopProcess 类了:

    class StopProcess implements Runnable {
        @Override
        public void run() {
            // do some needed work
        }
    } 
    

    然后你可以这样做:

    scheduler.schedule(new StopProcess(), 5, TimeUnit.SECONDS);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-30
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多