Referring to
How to add a timeout value when using Java's Runtime.exec()?
But I am always getting worker.exit value NULL so it always throws timeout exception. Below is my code
public class MyClass {
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;
}
}
}
public String run(String command, long replyTimeout) throws Exception {
StringBuffer output = new StringBuffer();
Process p;
p = Runtime.getRuntime().exec(command);
BufferedReader errReader = new BufferedReader(new InputStreamReader(
p.getErrorStream()));
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
Worker worker = new Worker(p);
worker.start();
try {
worker.join(replyTimeout);
if (worker.exit != null) {
if (worker.exit > 0) {
String line = "";
while ((line = errReader.readLine()) != null) {
output.append(line + "
");
}
System.out.println(output.toString());
System.out.println(worker.exit);
throw new Exception(output.toString());
} else {
String line = "";
while ((line = inputReader.readLine()) != null) {
output.append(line + "
");
}
System.out.println(output.toString());
System.out.println(worker.exit);
return output.toString();
}
} else {
throw new TimeoutException();
}
} catch (InterruptedException ex) {
worker.interrupt();
Thread.currentThread().interrupt();
throw ex;
} finally {
p.destroy();
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…