使用processBuilder执行shell命令并与之交互
private void execReloadAll(){
List<String> cmds = new ArrayList<String>();
commands.add("ls");
commands.add("-l");
commands.add("/");
ProcessBuilder pb=new ProcessBuilder(cmds);
int exitCode = 0;
try {
Process process = pb.start();
StreamGobbler streamGobbler =
new StreamGobbler(process.getInputStream(), System.out::println);
Executors.newSingleThreadExecutor().submit(streamGobbler);
exitCode = process.waitFor();
log.info(" 执行成功");
// 等待该进程执行完毕
if (exitCode != 0) {
// 如果进程运行结果不为0,表示进程是错误退出的
// 获得进程实例的错误输出
InputStream error = process.getErrorStream();
log.info("加载失败:{}",error);
throw new BizException(ErrorCode.IKE_LOAD_ALL_ERROR.getCode(),ErrorCode.IKE_LOAD_ALL_ERROR.getMsg());
}
// 获得进程实例的标准输出
InputStream sdin = process.getInputStream();
log.info("加载:{}",sdin);
} catch (Exception e) {
log.error("执行失败", e);
throw new BizException(ErrorCode.getCode(),ErrorCode.getMsg());
}
assert exitCode == 0;
}
|