2015-07-12 254 views

回答

2

可能的解決方案可能是資源管理器proc條目。的確,這就是top和其他人如何訪問正在運行的進程列表。

我不能完全肯定,如果這是你要找的,但它可以給你一些線索:

import java.awt.Desktop; 
    import java.io.BufferedReader; 
    import java.io.File; 
    import java.io.FileInputStream; 
    import java.io.FileNotFoundException; 
    import java.io.IOException; 
    import java.io.InputStreamReader; 

    public class OpenFolder { 
     public static void main(String[] args) throws IOException { 
      System.out.println(findProcess("process_name_here")); 
     } 

     public static boolean findProcess(String processName) throws IOException { 
      String filePath = new String(""); 
      File directory = new File("/proc"); 
      File[] contents = directory.listFiles(); 
      boolean found = false; 
      for (File f : contents) { 
       if (f.getAbsolutePath().matches("\\/proc\\/\\d+")) { 
        filePath = f.getAbsolutePath().concat("/status"); 
        if (readFile(filePath, processName)) 
         found = true; 
       } 
      } 
      return found; 
     } 

     public static boolean readFile(String filename, String processName) 
     throws IOException { 
      FileInputStream fstream = new FileInputStream(filename); 
      BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
      String strLine; 
      strLine = br.readLine().split(":")[1].trim(); 
      br.close(); 
      if (strLine.equals(processName)) 
       return true; 
      else 
       return false; 
     } 
    } 
+0

這是一個想法!猜猜你可以使用一些謂詞來使代碼更清晰,但我認爲這應該對我有用 – csny

0

不,沒有純java的方式如何做到這一點。原因可能是,這個過程是相當平臺相關的概念。請參閱How to get a list of current open windows/process with Java?(您也可以在Linux中找到有用的提示)

+0

Java是平臺獨立的,所以這不是原因。但我花了足夠的時間尋找解決方案,並沒有找到一個...所以我想'ps'它是。 – csny

1

在Java 9會有一個標準的API來解決這個問題稱爲ProcessHandle。您甚至可以嘗試下載JDK9預覽。下面是一個例子:

public class ps { 
    public static void main(String[] args) { 
    ProcessHandle.allProcesses() 
       .map(p -> p.getPid()+": "+p.info().command().orElse("?")) 
       .forEach(System.out::println); 
    } 
} 

它打印所有進程的pid和命令行(如果知道)。在Windows和Linux中運行良好。

相關問題