当前位置: 代码迷 >> J2SE >> 在linux环境下关于java获取进程PID的有关问题
  详细解决方案

在linux环境下关于java获取进程PID的有关问题

热度:40   发布时间:2016-04-24 12:14:35.0
在linux环境下关于java获取进程PID的问题
在java中怎样获得一个进程的PID,高手请指教。
我用Runtime.getruntime.exec(cmd)执行ps -aux为什么只能取到进程的标题信息,取不到具体每个进程的信息,为什么?
痛苦中~~~~~~~~~~~~~~~~~~~~~~~

------解决方案--------------------
你要自己读出输出结果才行
Java code
Process p = Runtime.getruntime.exec(cmd);BufferReader br = new BufferedRead(new InputStreamReader(p.getInputStream()));for (String buf=br.readLine(); buf != null; buf=br.readLine()) {    System.out.println(buf);}
------解决方案--------------------
Java code
import java.io.*;import java.util.regex.*;public class GetPID {    public static void main(String[] args) {        Process process = null;        BufferedReader br = null;        try {            process = Runtime.getRuntime().exec("ps -ef");            br = new BufferedReader(new InputStreamReader(                        process.getInputStream()), 1024);            String line = null;            Pattern pattern = Pattern.compile("\\S*\\s*([0-9]*).*");            Matcher matcher = null;            System.out.println("PID list: ");            while ((line = br.readLine()) != null) {                matcher = pattern.matcher(line);                if (matcher.find()) {                    System.out.println(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();                        }                    }                }            }        }    }}
  相关解决方案