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