2008-09-10 47 views

回答

86

这是另一种方法,从命令“PS -e”解析进程列表:

try { 
    String line; 
    Process p = Runtime.getRuntime().exec("ps -e"); 
    BufferedReader input = 
      new BufferedReader(new InputStreamReader(p.getInputStream())); 
    while ((line = input.readLine()) != null) { 
     System.out.println(line); //<-- Parse data here. 
    } 
    input.close(); 
} catch (Exception err) { 
    err.printStackTrace(); 
} 

如果您使用的是Windows,那么你应该更改行:“过程p = Runtime.getRun ......”等等......(3号线),一个看起来像这样:

Process p = Runtime.getRuntime().exec 
    (System.getenv("windir") +"\\system32\\"+"tasklist.exe"); 

希望的信息帮助!

+0

如何获取进程开始时间和结束时间 – Bucks 2012-09-11 09:27:04

+28

在Windows上,运行`tasklist.exe/fo csv/nh`获取CSV格式的列表,这更容易解析。 – 2013-01-24 15:31:21

+0

但它没有显示jar名称。我的可执行jar名称是helloDemo.jar。但它没有显示任何内容 – 2015-05-02 10:57:28

9

我能想到的唯一方法就是调用一个命令行应用程序,为您完成这项工作,然后对输出进行筛选(如Linux的ps和Window的任务列表)。

不幸的是,这意味着你将不得不编写一些解析例程来读取两者中的数据。

Process proc = Runtime.getRuntime().exec ("tasklist.exe"); 
InputStream procOutput = proc.getInputStream(); 
if (0 == proc.waitFor()) { 
    // TODO scan the procOutput for your data 
} 
+1

是的,我已经考虑过了,但是我很难用Java来完成它。 我想我会更好地使用“ps -aux”而不是top。感谢你及时的答复! – ramayac 2008-09-10 17:04:20

+0

在Windows上,`tasklist`程序可以配置为输出CSV :) – MauganRa 2017-03-10 08:41:17

4

这样做没有平台中立的方式。在1.6版本的Java中,增加了一个“Desktop”类,允许浏览,编辑,邮寄,打开和打印URI的便携方式。这个班可能有一天可能会扩展到支持流程,但我对此表示怀疑。

如果您只对Java进程感兴趣,则可以使用java.lang.management api获取JVM上的线程/内存信息。

7

YAJSW(然而,另一个Java服务包装)看起来有其org.rzo.yajsw.os.TaskList接口为Win32,Linux的,BSD和Solaris的基于JNA的实现,是在LGPL许可下。我没有试过直接调用这个代码,但是当我过去使用它时YAJSW运行得非常好,所以你不应该有太多的担忧。

23

在Windows上有使用JNA一种替代方案:

import com.sun.jna.Native; 
import com.sun.jna.platform.win32.*; 
import com.sun.jna.win32.W32APIOptions; 

public class ProcessList { 

    public static void main(String[] args) { 
     WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS); 

     WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); 

     Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); 

     while (winNT.Process32Next(snapshot, processEntry)) { 
      System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile)); 
     } 

     winNT.CloseHandle(snapshot); 
    } 
} 
3

使用代码来解析ps aux用于Linux和tasklist窗户是你最好的选择,直到更多的东西一般走来。

对于Windows,你可以参考一下:http://www.rgagnon.com/javadetails/java-0593.html

Linux的可管ps aux结果通过grep过,这将使加工/搜索方便快捷。我相信你也可以找到类似的窗口。

0
package com.vipul; 

import java.applet.Applet; 
import java.awt.Checkbox; 
import java.awt.Choice; 
import java.awt.Font; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

public class BatchExecuteService extends Applet { 
    public Choice choice; 

    public void init() 
    { 
     setFont(new Font("Helvetica", Font.BOLD, 36)); 
     choice = new Choice(); 
    } 

    public static void main(String[] args) { 
     BatchExecuteService batchExecuteService = new BatchExecuteService(); 
     batchExecuteService.run(); 
    } 

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

    public void run() { 
     try { 
      Runtime runtime = Runtime.getRuntime(); 
      Process process = runtime.exec("D:\\server.bat"); 
      process.getOutputStream().close(); 
      InputStream inputStream = process.getInputStream(); 
      InputStreamReader inputstreamreader = new InputStreamReader(
        inputStream); 
      BufferedReader bufferedrReader = new BufferedReader(
        inputstreamreader); 
      BufferedReader bufferedrReader1 = new BufferedReader(
        inputstreamreader); 

      String strLine = ""; 
      String x[]=new String[100]; 
      int i=0; 
      int t=0; 
      while ((strLine = bufferedrReader.readLine()) != null) 
      { 
     //  System.out.println(strLine); 
       String[] a=strLine.split(","); 
       x[i++]=a[0]; 
      } 
    //  System.out.println("Length : "+i); 

      for(int j=2;j<i;j++) 
      { 
       System.out.println(x[j]); 
      } 
     } 
     catch (IOException ioException) 
     { 
      ioException.printStackTrace(); 
     } 

    } 
} 
You can create batch file like 

TASKLIST/V/FI “STATUS当量运行”/ FO “CSV”/ FI “用户名当量LHPL002 \软”/ FI “MEMUSAGE GT 10000”/ FI“WINDOWTITLE NE N/A”/NH

5

可以使用jProcesses

List<ProcessInfo> processesList = JProcesses.getProcessList(); 

for (final ProcessInfo processInfo : processesList) { 
    System.out.println("Process PID: " + processInfo.getPid()); 
    System.out.println("Process Name: " + processInfo.getName()); 
    System.out.println("Process Used Time: " + processInfo.getTime()); 
    System.out.println("Full command: " + processInfo.getCommand()); 
    System.out.println("------------------"); 
} 
3

因为我使用下列窗口方便地检索正在运行的进程列表:

 Process process = new ProcessBuilder("tasklist.exe", "/fo", "csv", "/nh").start(); 
    new Thread(() -> { 
     Scanner sc = new Scanner(process.getInputStream()); 
     if (sc.hasNextLine()) sc.nextLine(); 
     while (sc.hasNextLine()) { 
      String line = sc.nextLine(); 
      String[] parts = line.split(","); 
      String unq = parts[0].substring(1).replaceFirst(".$", ""); 
      String pid = parts[1].substring(1).replaceFirst(".$", ""); 
      System.out.println(unq + " " + pid); 
     } 
    }).start(); 
    process.waitFor(); 
    System.out.println("Done"); 
4

最后,与Java 9有可能与ProcessHandle

public static void main(String[] args) { 
    ProcessHandle.allProcesses() 
      .forEach(process -> System.out.println(processDetails(process))); 
} 

private static String processDetails(ProcessHandle process) { 
    return String.format("%8d %8s %10s %26s %-40s", 
      process.pid(), 
      text(process.parent().map(ProcessHandle::pid)), 
      text(process.info().user()), 
      text(process.info().startInstant()), 
      text(process.info().commandLine())); 
} 

private static String text(Optional<?> optional) { 
    return optional.map(Object::toString).orElse("-"); 
} 

编辑: “将” → “是”

-1

同样的问题(Windows running application list using Java

我发现这个答案(https://stackoverflow.com/a/2206526)wmic.exe正常输出by Philippe

try{ 
     Process proc = Runtime.getRuntime().exec("wmic.exe"); 
     BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream())); 
     OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream()); 
     oStream.write("process get caption"); 
     oStream.flush(); 
     oStream.close(); 
     String line; 
     while ((line = input.readLine()) != null){ 
      if(!line.isEmpty() && !line.startsWith("wmic:root\\cli")) { 
       System.out.println(line); 
      } 
     } 
     input.close(); 
}catch (IOException ioe){ioe.printStackTrace();} 
相关问题