通过jna调用动态链接库的方式来获取pid,需要在代码里面导入一个jna-4.1.0.jar,对应的maven如下:
<dependency> <groupId>net.java.dev.jna</groupId> <artifactId>jna</artifactId> <version>4.1.0</version> </dependency>新建一个接口Kernel32,代码如下:
import com.sun.jna.Library; import com.sun.jna.Native; public interface Kernel32 extends Library{ public static Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class); public long GetProcessId(Long hProcess); }根据Process获取进程id,根据进程id杀死进程
package com.amt.content.production.utils; import com.sun.jna.Platform; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; @Slf4j public class ProcessUtil{ public static String getProcessId(Process process) { long pid = -1; Field field = null; if (Platform.isWindows()) { try { field = process.getClass().getDeclaredField("handle"); field.setAccessible(true); pid = Kernel32.INSTANCE.GetProcessId((Long) field.get(process)); } catch (Exception ex) { ex.printStackTrace(); } } else if (Platform.isLinux() || Platform.isAIX()) { try { Class<?> clazz = Class.forName("java.lang.UNIXProcess"); field = clazz.getDeclaredField("pid"); field.setAccessible(true); pid = (Integer) field.get(process); } catch (Throwable e) { e.printStackTrace(); } } return String.valueOf(pid); } /** * 关闭Linux进程 * @param pid 进程的PID */ public static boolean killProcessByPid(String pid){ if (StringUtils.isEmpty(pid) || "-1".equals(pid)) { throw new RuntimeException("Pid ==" + pid); } Process process = null; BufferedReader reader =null; String command = ""; boolean result = false; if (Platform.isWindows()) { command = "cmd.exe /c taskkill /PID " + pid + " /F /T "; } else if (Platform.isLinux() || Platform.isAIX()) { command = "kill -9 " + pid; } try{ //杀掉进程 process = Runtime.getRuntime().exec(command); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8")); String line = null; while((line = reader.readLine())!=null){ log.info("kill PID return info -----> "+line); } result = true; }catch(Exception e){ log.info("杀进程出错:", e); result = false; }finally{ if(process!=null){ process.destroy(); } if(reader!=null){ try { reader.close(); } catch (IOException e) { } } } return result; } }