如何检查某个进程是否正在运行 - java on linux

问题描述:

我需要检查一个非java进程是否正在运行(按进程名称)在一个java程序中 - 与Java - how to check whether another (non-Java) process is running on Linux中的问题非常相似。
解决方案没问题,但它仍然需要打开系统调用过程,我想避免这种情况。
是否有纯java方式来获取在Linux上运行的进程列表?如何检查某个进程是否正在运行 - java on linux

可能的解决方案可能是资源管理器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

不,没有纯java的方式如何做到这一点。原因可能是,这个过程是相当平台相关的概念。请参阅How to get a list of current open windows/process with Java?(您也可以在Linux中找到有用的提示)

+0

Java是平*立的,所以这不是原因。但我花了足够的时间寻找解决方案,并没有找到一个...所以我想'ps'它是。 – csny

在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中运行良好。