/** * * @author chenshu */ public class CommandHelper {
//default time out, in millseconds public static int DEFAULT_TIMEOUT; public static final int DEFAULT_INTERVAL = 1000; public static long START; public static CommandResult exec(String command) throws IOException, InterruptedException { Process process = Runtime.getRuntime().exec(command); CommandResult commandResult = wait(process); if (process != null) { process.destroy(); } return commandResult; }
//timeout control START = System.currentTimeMillis(); boolean isFinished = false;
for (;;) { if (isOverTime()) { CommandResult result = new CommandResult(); result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT); result.setOutput("Command process timeout"); return result; }
if (isFinished) { CommandResult result = new CommandResult(); result.setExitValue(process.waitFor());
//parse error info if (errorStreamReader.ready()) { StringBuilder buffer = new StringBuilder(); String line; while ((line = errorStreamReader.readLine()) != null) { buffer.append(line); } result.setError(buffer.toString()); }
//parse info if (inputStreamReader.ready()) { StringBuilder buffer = new StringBuilder(); String line; while ((line = inputStreamReader.readLine()) != null) { buffer.append(line); } result.setOutput(buffer.toString()); } return result; }