核心代碼(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 服務,便於測試與審計。