使用Java的Runtime.exec()时如何添加超时值?

我有一种用于在本地主机上执行命令的方法。我想向该方法添加一个超时参数,以便如果被调用的命令没有在合理的时间内完成,则该方法将返回错误代码。这是到目前为止的样子,无法超时:

public static int executeCommandLine(final String commandLine,

final boolean printOutput,

final boolean printError)

throws IOException, InterruptedException

{

Runtime runtime = Runtime.getRuntime();

Process process = runtime.exec(commandLine);

if (printOutput)

{

BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

System.out.println("Output: " + outputReader.readLine());

}

if (printError)

{

BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

System.out.println("Error: " + errorReader.readLine());

}

return process.waitFor();

}

谁能为我提出一种实现超时参数的好方法?

回答:

public static int executeCommandLine(final String commandLine,

final boolean printOutput,

final boolean printError,

final long timeout)

throws IOException, InterruptedException, TimeoutException {

Runtime runtime = Runtime.getRuntime();

Process process = runtime.exec(commandLine);

/* Set up process I/O. */

...

Worker worker = new Worker(process);

worker.start();

try {

worker.join(timeout);

if (worker.exit != null)

return worker.exit;

else

throw new TimeoutException();

} catch(InterruptedException ex) {

worker.interrupt();

Thread.currentThread().interrupt();

throw ex;

} finally {

process.destroyForcibly();

}

}

private static class Worker extends Thread {

private final Process process;

private Integer exit;

private Worker(Process process) {

this.process = process;

}

public void run() {

try {

exit = process.waitFor();

} catch (InterruptedException ignore) {

return;

}

}

}

以上是 使用Java的Runtime.exec()时如何添加超时值? 的全部内容, 来源链接: utcz.com/qa/428753.html

回到顶部