首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 一鍵殺進程:Runtime.exec 實現 taskkill 跨平台封裝

     編輯:Java 相關知識

核心代碼(Windows)

// 強制殺掉 firefox 進程
Runtime.getRuntime().exec("taskkill /F /IM firefox.exe");

// 強制殺掉 QQ 進程
Runtime.getRuntime().exec("taskkill /F /IM qq.exe");

參數解析

參數含義
/F強制終止(相當 Linux kill -9)
/IM指定映像名稱(進程可執行文件名)
/PID指定進程 ID(替代 /IM)
/T樹狀殺掉:同時終止子進程

跨平台封裝工具類

import java.io.IOException;

public class ProcessKiller {
    public static boolean killByName(String processName) {
        String os = System.getProperty("os.name").toLowerCase();
        String cmd;
        if (os.contains("win")) {
            cmd = String.format("taskkill /F /IM %s", processName);
        } else if (os.contains("linux") || os.contains("mac")) {
            // pkill 支援進程名模糊匹配,-9 強制殺掉
            cmd = String.format("pkill -9 -f %s", processName);
        } else {
            throw new UnsupportedOperationException("不支援的作業系統: " + os);
        }

        try {
            Process process = Runtime.getRuntime().exec(cmd);
            int exitCode = process.waitFor();
            return exitCode == 0;
        } catch (IOException | InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    public static boolean killByPid(long pid) {
        String os = System.getProperty("os.name").toLowerCase();
        String cmd = os.contains("win") 
            ? String.format("taskkill /F /PID %d", pid)
            : String.format("kill -9 %d", pid);
        try {
            return Runtime.getRuntime().exec(cmd).waitFor() == 0;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println("Kill firefox: " + killByName("firefox.exe"));
        System.out.println("Kill chrome:  " + killByName("chrome"));
    }
}

進階:純 Java 方案 (JDK 9+ ProcessHandle)

import java.lang.ProcessHandle;
import java.util.Optional;

public class ModernProcessKiller {
    /** 進程名精確匹配殺掉 */
    public static int killByExactName(String name) {
        return (int) ProcessHandle.allProcesses()
            .filter(ph -> ph.info().command().orElse("").endsWith(name))
            .mapToInt(ph -> ph.destroyForcibly() ? 1 : 0)
            .sum();
    }

    /** 進程名模糊匹配殺掉 */
    public static int killByPartialName(String keyword) {
        return (int) ProcessHandle.allProcesses()
            .filter(ph -> ph.info().command().orElse("").contains(keyword))
            .mapToInt(ph -> ph.destroyForcibly() ? 1 : 0)
            .sum();
    }

    /** PID 精確殺掉 */
    public static boolean killByPid(long pid) {
        return ProcessHandle.of(pid)
            .map(ph -> ph.destroyForcibly())
            .orElse(false);
    }
}

方案對比

方案優點缺點適用版本
Runtime.exec + taskkill/pkill簡單、兼容舊版本依賴系統命令、需解析輸出JDK 1.5+
ProcessHandle API純 Java、跨平台、流式 API、可獲取進程元數據需 JDK 9+JDK 9+

安全與權限提醒

  • 殺進程需對應 OS 權限(Windows 需管理員、Linux 需 root/sudo)
  • 生產環境嚴禁硬編碼殺核心進程(如 java、systemd、init)
  • 建議加入白名單校驗,防止誤殺
  • 記錄操作日誌:操作者、目標進程、時間、結果

總結

Java 殺進程兩大流派:舊版本靠 Runtime.exec 呼叫系統命令,JDK 9+ 首選 ProcessHandle 純 Java API。工具類封裝時務必做 OS 判斷、權限檢查、白名單保護、結果日誌。避免在業務邏輯中直接硬編碼 taskkill,應抽象為 ProcessManager 服務,便於測試與審計。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved