1. 程式人生 > >關於Java中Process類和Runtime.exec()的一些使用

關於Java中Process類和Runtime.exec()的一些使用

在Android中有一個需求,有幾個二進位制可執行檔案要執行,並作為單獨的程序跑在後臺,需要監聽它們的狀態,如果意外終止,要重啟它們。
  啟動程式碼大致如下所示:

Runtime.getRuntime().exec("chmod 777 " + mContext.getApplicationContext().
        getApplicationContext().getFilesDir().getAbsolutePath() + "/" + copyFileNameList.get(i));
Process process = Runtime.getRuntime().exec(mContext.getApplicationContext().
        getFilesDir().getAbsolutePath() + "/" + copyFileNameList.get(i) + " " + copyFileExArgs.get(i));  

  Runtime.getRuntime().exec()相當於你可以在Java程式中執行Linux終端中的命令,chmod給許可權,這裡不展開說,然後我們就可以得到一個Process物件。
  想拿到程序PID,檢視API:http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html ,發現沒有獲得PID的方法,不過通過:

System.out.println(process.toString())  

  的輸出結果:

Process[pid=2869]  

  稍微解析下就OK,程式碼如下:

public int getPIDFromProcessToString(String s) {
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
            stringBuilder.append(s.charAt(i));
        }
    }
    return Integer.valueOf(stringBuilder.toString());
}  

  那麼如何在程序意外終止,重啟它們。
  
  方法一是輪詢,從proc目錄中我們可以獲得正在執行程序的PID,程式碼如下:

public HashMap<Integer, Integer> getRunningPIDFromProc() {
    HashMap<Integer, Integer> hashMap = new HashMap<>();
    File file = new File("/proc");
    File[] files = file.listFiles();
    for (File temp : files) {
        if (stringIsDigit(temp.getName())) {
            hashMap.put(Integer.valueOf(temp.getName()), 0);
        }
    }
    return hashMap;
}  

  將程序PID作為HashMap的key值,通過下面程式碼每個一段時間判斷下即可:

!hashMap.containsKey(zSXSharedPreferences.getInt(copyFileNameList.get(i) + "_pid", -1))  

  如果掛掉了,重啟即可。具體實現的時候開個執行緒即可,具體程式碼大概如下:

// polling thread
new Thread(new Runnable() {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(15*60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("polling thread");
            HashMap<Integer, Integer> hashMap = getRunningPIDFromProc();
            for (int i = 0; i < copyFileNameList.size(); i++) {

                System.out.println("PID in SharedPreferences:" + zSXSharedPreferences.getInt(copyFileNameList.get(i) + "_pid", -1));
                if (!hashMap.containsKey(zSXSharedPreferences.getInt(copyFileNameList.get(i) + "_pid", -1))) {
                    System.out.println(mContext.getApplicationContext().
                            getApplicationContext().getFilesDir().getAbsolutePath() + "/" +
                            copyFileNameList.get(i) + " " + copyFileExArgs.get(i));
                    Process process = null;
                    try {
                        process = Runtime.getRuntime().exec(mContext.getApplicationContext().
                                getApplicationContext().getFilesDir().getAbsolutePath() + "/" +
                                copyFileNameList.get(i) + " " + copyFileExArgs.get(i));
                        System.out.println(process.toString() + "***");
                        zSXEditor.putInt(copyFileNameList.get(i) + "_pid",
                                getPIDFromProcessToString(process.toString()));
                        zSXEditor.commit();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }
}).start();  

  方法二可以藉助Process.waitFor()方法。具體就是開個執行緒來啟動我們要啟動的程序,然後在Process.waitFor()後再遞迴呼叫這個過程,這樣當我們的程序被殺死後,就又可以被啟動了,如果覺得馬上就啟動太明顯的話,還可以做個延時,過段時間再啟動,具體見下面的程式碼:

public void startThreadForProcess(final int finalI,final List<String> copyFileNameList,
                                  final List<String> copyFileExArgs,
                                  final SharedPreferences.Editor zSXEditor) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            Process process = null;
            try {
                process = Runtime.getRuntime().exec(mContext.getApplicationContext().
                        getApplicationContext().getFilesDir().getAbsolutePath() + "/" +
                        copyFileNameList.get(finalI) + " " + copyFileExArgs.get(finalI));
                System.out.println(process.toString() + "**");
                zSXEditor.putInt(copyFileNameList.get(finalI) + "_pid", getPIDFromProcessToString(process.toString()));
                try {
                    System.out.println("process.waitFor()");
                    process.waitFor();
                    System.out.println("process.waitFor() stop");
                    startThreadForProcess(finalI,copyFileNameList,copyFileExArgs,zSXEditor);
                } catch (InterruptedException e) {
                    System.out.println("process.waitFor() InterruptedException");
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}