我想要通过命令行执行一个程序 类似于 java -jar xxx.jar,然后获得该程序的进程 ID ,并稍后通过进程 ID 判断该进程是否存活。
//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);
}
最后我希望通过进程 id 判断该进程是否存活,但是我在查进程的时候发现 根本查不到我的那个进程号
// 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)){
//输出流中读不到我之前获得的那个进程 ID
return true;
}
}
} catch (IOException e) {
//exception handle
}
}