我正在使用 Java 程式中的 DefaultExecutor 和 CommandLine 執行 shell 腳本。
成功執行接收 0 退出值
但是如果發生故障或來自 shell 腳本的任何其他退出代碼(如 127,128,255 等),則不會收到相應的退出代碼,而是獲取 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);
}
任何想法如何處理退出代碼以執行特定的自定義操作?
uj5u.com熱心網友回復:
的檔案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);
}
uj5u.com熱心網友回復:
在探索更多之后,我能夠找出正確的答案。
對于成功退出代碼,將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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341834.html
上一篇:解密檔案gpg時添加進度條
