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

How to check is a certain process is running - java on linux

我需要检查 java 程序中的非 java 进程是否为 运行(按进程名称)- 与 Java - how to check whether another (non-Java) process is running on Linux 中的问题非常相似.
解决方法是可以的,但是还是需要开启一个系统调用进程,我想避免这种情况。
是否有一种纯粹的 java 方法来获取 linux 上的 运行 进程列表?

不,没有纯粹的java方法可以做到这一点。这样做的原因可能是,进程是非常依赖于平台的概念。请参阅 How to get a list of current open windows/process with Java?(您还可以在那里找到 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;
        }
    }

在 Java 9 及更高版本中有一个标准 API 来解决这个问题,称为 ProcessHandle。这是一个例子:

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 中工作正常。