process.waitFor(timeout, timeUnit) 在指定时间后不会退出进程



我正在尝试使用进程生成器在我的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 

}

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((。

最新更新