我需要检查一个非java进程是否正在java程序中运行(进程名)-非常类似于Java - how to check whether another (non-Java) process is running on Linux中的问题。
解决方案是可以的,但它仍然需要打开一个系统调用进程,我想避免这种情况。
是否有一种纯java的方法来获取在linux上运行的进程列表?
发布于 2015-07-13 11:49:39
一个可能的解决方案可能是资源管理器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;
}
}发布于 2015-07-14 05:09:57
在Java9和更高版本中,有一个标准的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中工作得很好。
发布于 2015-07-12 11:12:52
不,没有纯java的方法可以做到这一点。原因可能是,过程是非常依赖于平台的概念。请参阅How to get a list of current open windows/process with Java? (您也可以在那里找到有用的Linux技巧)
https://stackoverflow.com/questions/31366975
复制相似问题