57 lines
1.9 KiB
Java
57 lines
1.9 KiB
Java
package io.gitlab.jfronny.inceptum.launcher.util;
|
|
|
|
import io.gitlab.jfronny.commons.OSUtils;
|
|
import io.gitlab.jfronny.inceptum.common.Utils;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.InputStreamReader;
|
|
|
|
public class ProcessUtils {
|
|
public static boolean isProcessAlive(String pid) {
|
|
if (OSUtils.TYPE == OSUtils.Type.WINDOWS)
|
|
return isProcessIdRunning(pid, "tasklist", "/FI", "PID eq " + pid);
|
|
return isProcessIdRunning(pid, "ps", "-p", pid);
|
|
}
|
|
|
|
public static boolean kill(String pid) {
|
|
//TODO test on windows
|
|
if (OSUtils.TYPE == OSUtils.Type.WINDOWS)
|
|
return kill("taskkill", "/f", "/pid", pid);
|
|
return kill("kill", "--timeout", "500", "KILL", pid);
|
|
}
|
|
|
|
private static boolean isProcessIdRunning(String pid, String... command) {
|
|
try {
|
|
Runtime rt = Runtime.getRuntime();
|
|
Process pr = rt.exec(command);
|
|
|
|
try (InputStreamReader isReader = new InputStreamReader(pr.getInputStream());
|
|
BufferedReader bReader = new BufferedReader(isReader)) {
|
|
String strLine;
|
|
while ((strLine = bReader.readLine()) != null) {
|
|
if (strLine.contains(" " + pid + " ")) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
} catch (Exception e) {
|
|
Utils.LOGGER.error("Could not get process state", e);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
private static boolean kill(String... command) {
|
|
try {
|
|
Runtime rt = Runtime.getRuntime();
|
|
Process pr = rt.exec(command);
|
|
pr.waitFor();
|
|
Thread.sleep(100); // Ensure the signal is processed by waiting this randomly picked amount of time
|
|
return pr.exitValue() == 0;
|
|
} catch (Exception e) {
|
|
Utils.LOGGER.error("Could not kill process", e);
|
|
return false;
|
|
}
|
|
}
|
|
}
|