在做RPA時,我知道了一個進程ID,但我想知道這個進程ID是否一直還在
經(jīng)查狰挡,方法如下:
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;
}
上述方法,無論系統(tǒng)是linux,還是windows,就能查到進程是否存在