I want to execute a program through the command line similar to java -jar xxx.jar
then get the process ID of the program
judge whether the process is alive or not by the process ID later.
//start a process
String command = "...";
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
//get the pid of process
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
field = clazz.getDeclaredField("pid");
ReflectionUtils.makeAccessible(field);
pid = (Integer) field.get(process);
}
Then, i want to determine if this process is alive,i tried like:
// judge the process is alive or not. By pid.
if (System.getProperty(Constants.SYSTEM_NAME).toLowerCase().contains("linux") || System.getProperty(Constants.SYSTEM_NAME).toLowerCase().contains("mac")) {
process = RuntimeUtil.exec(BIN_BASH + " -c" + " ps -elf | grep " + pid);
}
if(process != null){
String line;
try(InputStream in = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in,StandardCharsets.UTF_8))){
while((line = br.readLine()) != null){
if(line.contains(pid)){
// i can't see the pid of my process (always)
return true;
}
}
} catch (IOException e) {
//exception handle
}
}