![](/img/trans.png)
[英]How to detect via Java whether a particular process is running under Windows?
[英]How to find whether a process is running on Windows/Linux
我希望我的程序能够检测OBS-Studio当前是否正在运行,如果正在运行,请在我的程序中执行某些功能。 问题是我似乎找不到能够在两个平台上都适用的解决方案。 我发现在Windows上使用taskList
, wmic.exe
和其他工具,在Linux上使用top
, ps aux
和其他工具,但是这些都是特定于平台的,并且不容易移植。 有通用的用例吗?如果有,那会是什么?
我知道Java9 +中的ProcessHandle,但是我的程序运行Java8,目前没有升级的希望,所以这是不可能的。
我想不出一个在两个平台上都可以使用的解决方案,也许可以使用如下所示的方法来确定Java的操作系统,然后再从那里使用条件语句来执行适用于您的主机的部分代码。
os = System.getProperty("os.name");
我希望这有帮助
我最终创建了一个方法,该方法通过运行os-specific命令为所有进程返回Map<Integer, String>
:
public Map<Integer, String> getProcesses() {
final Map<Integer, String> processes = Maps.newHashMap();
final boolean windows = System.getProperty("os.name").contains("Windows");
try {
final Process process = Runtime.getRuntime().exec(windows ? "tasklist /fo csv /nh" : "ps -e");
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
reader.lines().skip(1).forEach(x -> { // the first line is usually just a line to explain the format
if (windows) {
// "name","id","type","priority","memory?"
final String[] split = x.replace("\"", "").split(",");
processes.put(Integer.valueOf(split[1]), split[0]);
}
else {
// id tty time command
final String[] split = Arrays.stream(x.trim().split(" ")).map(String::trim)
.filter(s -> !s.isEmpty()).toArray(String[]::new); // yikes
processes.put(Integer.valueOf(split[0]), split[split.length - 1]);
}
});
}
}
catch (IOException e) {
e.printStackTrace();
}
return processes;
}
尚未在Windows上对其进行测试,但是应该可以使用。 除了Linux以外,它还没有在其他任何东西上进行过测试,但是我希望这可以为其他人提供有用的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.