【问题标题】:process.waitFor(timeout, timeUnit) does not quit the process after specified timeprocess.waitFor(timeout, timeUnit) 在指定时间后不退出进程
【发布时间】:2020-01-17 12:34:14
【问题描述】:

我正在尝试使用进程构建器在我的 Java 应用程序中执行 Visual Basic 脚本代码。由于用户提供的脚本可能无法及时完成其执行,我想提供限制此执行时间的方法。在下面的代码中,您可以看到我的逻辑,但它并没有真正做到它应该做的事情。我怎样才能让这个等待工作以限制执行时间?

private void run(String scriptFilePath) throws ScriptPluginException {
BufferedReader input = null;
BufferedReader error = null;

try {

    ProcessBuilder p = new ProcessBuilder("cscript.exe", "//U", "\"" + scriptFilePath + "\"");

    String path = "";

    if (scriptFilePath.indexOf("/") != -1) {
        path = scriptFilePath.substring(0, scriptFilePath.lastIndexOf("/"));
    }

    path += "/" + "tempvbsoutput.txt";
    p.redirectOutput(new File(path));
    Process pp = p.start();

    try {
        pp.waitFor(executionTimeout, TimeUnit.MINUTES);     
    } catch (InterruptedException e) {
        SystemLog.writeError(jobId, ScriptConsts.COMPONENT_ID, "VBScriptExecutor", "run", 80401104,
                "VB Script executes fail.");
    } 

    if (!pp.isAlive()) {
        pp.getOutputStream().close();
    }

    // rest of the code flow 

}

【问题讨论】:

  • “但它并没有真正做到它应该做的事情”你认为它应该做什么,而它又做了什么?
  • 当脚本执行时间超过waitfor方法指定的时间时,应该终止其执行。我看不出有任何理由说明上面的文字不清楚。
  • The Javadoc of waitFor 表示“如有必要,使当前线程等待,直到此 Process 对象表示的子进程终止,或指定的等待时间过去。” (强调补充)。如果时间过去了,它不会说进程终止。

标签: java multithreading processbuilder java-threads


【解决方案1】:

Process.waitFor(long, TimeUnit) 一直等到进程终止或经过指定的时间 (Javadoc)。返回值表示进程是否退出。

if (process.waitFor(1, TimeUnit.MINUTES)) {
    System.out.println("process exited");
} else {
    System.out.println("process is still running");
}

waitFor() 在时间过去后不会杀死进程。

如果要终止子进程,请使用destroy()destroyForcibly()

【讨论】:

    猜你喜欢
    • 2019-05-04
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多