我正在使用DefaultExecutor执行shell脚本&
对于成功执行接收0退出值
,但如果失败或任何其他退出代码(如127,128,255等)从shell脚本中,没有收到相应的退出代码,而是得到IOException.
int iExitValue = 1;
CommandLine cmd = CommandLine.parse("sh /Users/DpakG/scripts/do_Database_Operations.sh");
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(cmd);
log.info("Script Exit Code: " + iExitValue);
} catch (IOException e) {
log.error("IOException occurred: ", e);
}
任何想法如何处理退出代码来执行特定的自定义操作?
DefaultExecutor::execute()
的文档说它抛出
ExecuteException—子进程执行失败或子进程返回一个退出值表明失败
ExecuteException是IOException
的子类,因此它会被你的代码捕获。如果您尝试(也)捕获正确的异常,您可以使用它的getExitValue()
方法来获取退出状态。
int iExitValue = 1;
CommandLine cmd = CommandLine.parse("sh /Users/DpakG/scripts/do_Database_Operations.sh");
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
oDefaultExecutor.setExitValue(0);
try {
iExitValue = oDefaultExecutor.execute(cmd);
log.info("Script succeeded with exit code " + iExitValue); // Always successful (0)
} catch (ExecuteException e) {
log.info("Script failed with exit code " + e.getExitValue());
} catch (IOException e) {
log.error("IOException occurred: ", e);
}
经过进一步探索,我终于找到了正确的答案。
成功为<<p> strong> 使用setExitValues()用int数组的成功码代替'setExitValue()',用单个退出码作为整数值。int[] codes = {0,127,128};
oDefaultExecutor.setExitValues(codes);
失败的剩余部分退出码将在ExecuteException块
中捕获catch (ExecuteException exe) {
iExitValue = exe.getExitValue();
log.info("Script failed with exit code: " + iExitValue);
}
带解决方案的完整代码片段
int iExitValue = 1;
CommandLine cmd = CommandLine.parse("sh /Users/DpakG/scripts/do_Database_Operations.sh");
DefaultExecutor oDefaultExecutor = new DefaultExecutor();
int[] successCodes = {0,127,128};
oDefaultExecutor.setExitValues(successCodes);
try {
iExitValue = oDefaultExecutor.execute(cmd);
log.info("Script succeeded with exit code " + iExitValue); // Either 0, 127 or 128
} catch (ExecuteException exe) {
iExitValue = exe.getExitValue();
log.info("Script failed with exit code: " + iExitValue);
} catch (IOException ie) {
log.error("IOException occurred: ", ie);
}