I'm trying to kill off a already running java process using the Name of the .jar file.
It works completely fine when running the command
pkill -9 -f myapp.jar
from terminal but it doesn't work when you run that same command in a ProcessBuilder.
BufferedReader killStream;
String line;
try{
String[] args = new String[] {"pkill", "-9", "-f", " myapp.jar"};
Process proc = new ProcessBuilder(args).start();
killStream = new BufferedReader(new InputStreamReader(proc.getInputStream()));
line = killStream.readLine();
System.out.println(line);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
killStream always return 'null'
What am i doing wrong here?
There are a few missing points here, aside from what is mentioned above regarding the passing in of the arguments your code could do with some more refining.
First of all why not use a try with resources clause to make sure that your resources are managed automatically and get always closed correctly?
With this in mind your code would look like:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
// code to parse the command's output.
} catch (IOException e) {
// code to handle exceptions
}
Secondly, with the current code your method will always return true even if the pkill
command has not run correctly.
Ideally would should wait for the process to terminate using Process#waitFor
and then invoke Process#exitValue
to retrieve the exit status of the command. Then you should return true or false based on whether the exit code is 0 or anything else.
Finally in order to be a bit more efficient, I would suggest using a StringBuilder
to collect and append all of the process's output lines and just printing out that String.
Note that there are even better methods to encapsulate all this procedures making it more generic and re-usable while also using Java 8+ API (like streams, consumers etc etc).