I have used OSHI libraries available, but the getProcessID function is not working. I need to find the PID of a process entered by the user.
I have now used this code
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;
}
This fails for processes with multiple instances running such as Chrome. So, how do I get Parent ProcessID or a process with a space in between the name?
Don’t use tasklist.exe. Use the ProcessHandle class. Not only will your code be shorter and easier to maintain, it will also work on systems other than Windows, with no additional effort.
Also, don’t use a varargs argument when you only want zero or one values. Use method overloads for that.