java 通過進程ID判斷進程是否存在

在做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,就能查到進程是否存在

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容