Reputation: 449
I'm using the following code in Java to kill two different Windows process by window title:
String cmd = "taskkill /F /FI \"WindowTitle eq " + windowTitle + "\" /T";
Process process = Runtime.getRuntime().exec(cmd);
In the first case, system produces cmd command -> taskkill /F /FI "WindowTitle eq X*" /T
and the process is killed successfully producing exit code of 0
.
In the seconds case, system produces cmd command -> taskkill /F /FI "WindowTitle eq Y*" /T
but the process remains alive and produces exit code of 255
.
Both processes are produced by the same software vendor.
Why would one process be killed while the other one refuses to die?
Thanks
Upvotes: 1
Views: 328
Reputation: 9463
Just triggering the process as you do will very likely get stuck. This is not directly related to Java but how operating systems treat processes if their streams are not handled (see https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Process.html).
So once you start a process, wait until it finishes. While waiting, ensure its stdout and stderr streams are cleared so the OS will not block the process.
While this answer does not tell you why sometimes processes get killed and sometimes not, I am sure once you try this there is enough information in your java output so you can figure it out.
The code could look something like this:
Process process = Runtime.getRuntime().exec(cmd);
InputStream pin = process.getInputStream();
InputStream perr = process.getErrorStream();
byte[] buffer = new byte[4096];
int read = 0;
while (process.isAlive()) {
read = pin.read(buffer); // empty stdout so process can run
if (read > 0) {
System.out.write(buffer, 0, read);
}
read = perr.read(buffer); // empty stderr so process can run
if (read > 0) {
System.err.write(buffer, 0, read);
}
}
// empty buffers one last time
read = pin.read(buffer);
while (read >= 0) {
System.out.write(buffer, 0, read);
read = pin.read(buffer);
}
read = perr.read(buffer);
while (read >= 0) {
System.err.write(buffer, 0, read);
read = perr.read(buffer);
}
// print process exit code
System.out.println("exited with "+process.getExitValue());
Upvotes: 1