为Process.waitFor设置超时
生活随笔
收集整理的這篇文章主要介紹了
为Process.waitFor设置超时
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
Java中在使用Runtime.getRuntime().exec(command)調用系統命令后
一般會調用Process.waitFor()來等待命令執行結束 獲取執行結果
今天一個悲劇的事實證明了
即使只是調用了很簡單的腳本命令
在調用Process.waitFor()后同樣可能發生無休止或者接近于無休止的阻塞
處理完故障之后痛定思痛
決定在代碼中加入超時控制
但是Process.waitFor()本身并不支持超時時間設置
一個方法是改用非阻塞的Process.exitValue()方法
然后輪詢檢查進程狀態 這種方式比較消耗CPU
以至于輪詢間隔也不能設置得太小 總歸不是很完美
另外就是多起一個線程
借助于其他的超時機制來控制
最后使用的代碼如下
public class ProcessUtils {/*** 運行一個外部命令,返回狀態.若超過指定的超時時間,拋出TimeoutException* @param command* @param timeout* @return* @throws IOException* @throws InterruptedException* @throws TimeoutException*/public static int executeCommand(final String command, final long timeout) throws IOException, InterruptedException, TimeoutException {Process process = Runtime.getRuntime().exec(command);Worker worker = new Worker(process);worker.start();try {worker.join(timeout);if (worker.exit != null){return worker.exit;} else{throw new TimeoutException();}} catch (InterruptedException ex) {worker.interrupt();Thread.currentThread().interrupt();throw ex;} finally {process.destroy();}}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;}}}}
轉載于:https://my.oschina.net/u/220934/blog/303867
總結
以上是生活随笔為你收集整理的为Process.waitFor设置超时的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 学习HTML5之塔克大战(详细记录)
- 下一篇: 敏捷个人手机应用:如何使用时中法目标