在java中怎样获得一个进程的PID,高手请指教。
我用Runtime.getruntime.exec(cmd)执行ps -aux为什么只能取到进程的标题信息,取不到具体每个进程的信息,为什么?
痛苦中~~~~~~~~~~~~~~~~~~~~~~~

解决方案 »

  1.   

    你需要什么信息?用 ps -ef 试试看
      

  2.   

    你要自己读出输出结果才行
    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);
    }
      

  3.   


    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();
    }
    }
    }
    }
    }
    }
    }这样似乎可以,运行如下:
    PID list: 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    ...