在做RPA时,我知道了一个进程ID,但我想知道这个进程ID是否一直还在
经查,方法如下:
public static boolean checkProcess(String processId) {
boolean flag = false;
Process process = null;
String command = "";
try {
if (Platform.isWindows()) {
command ="cmd /c tasklist /FI \"PID eq " + processId + "\"";
} else if (Platform.isLinux() || Platform.isAIX()) {
command = "ps aux | awk '{print $2}'| grep -w " + processId;
}
process = Runtime.getRuntime().exec(command);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream os = process.getInputStream();) {
byte[] b = new byte[256];
while (os.read(b) > 0) {
baos.write(b);
}
String s = baos.toString();
return s.contains(processId);
}
} catch (IOException e) {
log.error(processId, e);
} finally {
if (process != null) {
process.destroy();
}
}
return flag;
}
上述方法,无论系统是linux,还是windows,就能查到进程是否存在