关于Java中Process类和Runtime.exec()的一些使用

来源:互联网 发布:mac 复制照片到u盘 编辑:程序博客网 时间:2024/05/16 15:29

在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 threadnew 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();}  
0 0