Firstly, I ran the sample.jar with "java -jar sample.jar" command in bash.
Then trying to execute the "ps -ef | grep "sample.jar"" command in Linux with Java and to get the process ID on which the sample.jar is running.
String cmd = "ps -ef | grep \"sample.jar\"";
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
But by the following code I couldn't find the process ID:
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
String s = null;
if ((s = stdInput.readLine()) != null) {
String str[] = s.split("\\s+", 3);
String processId = str[1]; // I need this processId
rt.exec("kill " + processId);
}
I want to find the process id and kill the process. So that I can re-run my spring boot project on the same port.
Instead of using kill
, you can use the proc.destroy()
or the proc.forciblyDestroy()
methods, which does effectively the same thing and has the added bonus of being cross platform!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.