如何让进程运行在Windows中使用Java的PID



我已经使用了可用的OSHI库,但是getProcessID函数不起作用。我需要找到用户输入的进程的PID。

我现在使用了这个代码
public static String getProcessPID(String processName, boolean... ignoreLetterCase) {
String pid = "";
boolean ignoreCase = true;
if (ignoreLetterCase.length > 0) {
ignoreCase = ignoreLetterCase[0];
}
// Acquire the Task List from Windows
ProcessBuilder processBuilder = new ProcessBuilder("tasklist.exe");
Process process;
try {
process = processBuilder.start();
}
catch (java.io.IOException ex) {
return "";
}
// Read the list and grab the desired PID
String tasksList;
try (Scanner scanner = new Scanner(process.getInputStream(), "UTF-8").useDelimiter("\A")) {
int counter = 0;
String strg = "";
while (scanner.hasNextLine()) {
strg = scanner.nextLine();
// Uncomment the line below to print the current Tasks List to Console Window.
// System.out.println(strg);
if (!strg.isEmpty()) {
counter++;
if (counter > 2) {
if (ignoreCase) {
if (strg.toLowerCase().contains(processName.toLowerCase())) {
String[] tmpSplit = strg.split("\s+");
pid += (pid.isEmpty()) ? tmpSplit[1] : ", " + tmpSplit[1];
}
}
else {
if (strg.contains(processName)) {
String[] tmpSplit = strg.split("\s+");
pid += (pid.isEmpty()) ? tmpSplit[1] : ", " + tmpSplit[1];
}
}
}
}
}
}
return pid;
}

对于运行多个实例的进程(如Chrome),此操作失败。那么,如何获得Parent ProcessID或名称之间带有空格的进程呢?

不要使用tasklist.exe。使用proceshandle类。你的代码不仅会更短,更容易维护,而且还可以在Windows以外的系统上运行,而不需要额外的努力。

同样,当您只想要0或1个值时,不要使用varargs参数。使用方法重载。

public static OptionalLong getProcessPID(String processName) {
return getProcessPID(processName, true);
}
public static OptionalLong getProcessPID(String processName, boolean ignoreLetterCase) {
Predicate<String> matcher = cmd -> (ignoreLetterCase
? cmd.toLowerCase().contains(processName.toLowerCase())
: cmd.contains(processName));
try (Stream<ProcessHandle> processes = ProcessHandle.allProcesses()) {
return processes
.filter(p -> p.info().command().filter(matcher).isPresent())
.mapToLong(p -> p.pid())
.findFirst();
}
}

最新更新