我需要检查一个非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;
}
}https://stackoverflow.com/questions/31366975
复制相似问题