Windows与Linux获取进程集合的方法

Windows:

    List<String> tasklist=new ArrayList<String>();

    try {
      Process process = Runtime.getRuntime().exec(cmdstr);
      BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
      while (in.hasNextLine()) {
      String p = in.nextLine();
                     if (p.contains("java.exe")) {
                          p = p.replaceAll("\\s+", ",");
                          String[] arr = p.split(",");
                          tasklist.add(arr[1]);//此处要进行判断
                    }
             }
             in.close();

Centos:

  public static List<String> getPidFromCentos(){
            List<String> tasklist=new ArrayList<String>();
            Process process = null;
            BufferedReader br = null;
            try {
                String[] cmd ={"sh","-c","ps -ef | grep java"};
                process = Runtime.getRuntime().exec(cmd);
                br = new BufferedReader(new InputStreamReader(
                            process.getInputStream()), 1024);
                String line = null;
                Pattern pattern = Pattern.compile("\\S*\\s*([0-9]*).*");
                Matcher matcher = null;
                while ((line = br.readLine()) != null) {
                    matcher = pattern.matcher(line);
                    if (matcher.find()) {
                        tasklist.add(matcher.group(1));
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (process != null) {
                    int retval = 0;
                    try {
                        retval = process.waitFor();
                        System.out.println("retval = " + retval);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        if (br != null) {
                            try {
                                br.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            return tasklist;
        }

  

posted @ 2017-06-23 11:17  ginkgolu  阅读(219)  评论(0编辑  收藏  举报