關於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();
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章