Java获取系统中运行的进程
java9以下
public static void main(String[] args) {
try {
String line;
Process p;
//如果是windows
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
p = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "tasklist.exe");
} else {
p = Runtime.getRuntime().exec("ps -e");
}
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //打印运行程序
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
}
java9及以上
public static void main(String[] args) {
ProcessHandle.allProcesses()
.forEach(process -> System.out.println(processDetails(process)));
}
private static String processDetails(ProcessHandle process) {
return String.format("%8d %8s %10s %26s %-40s",
process.pid(),
text(process.parent().map(ProcessHandle::pid)),
text(process.info().user()),
text(process.info().startInstant()),
text(process.info().commandLine()));
}
private static String text(Optional<?> optional) {
return optional.map(Object::toString).orElse("-");
}
Loading...