有一种更精简的方法可以使用 Java JNA 来完成此操作。
这绝对适用于 Windows 和 Linux,我认为您也可以对其他平台执行相同的操作。
Java进程处理的最大问题是缺少一种方法来获取由untime.getRuntime().exec()启动的进程的进程ID。
假设你得到了一个进程的pid,你总是可以在linux中启动kill -9命令,或者在windows中使用类似的方法来终止进程。
这是一种在 Linux 上获取本机进程 id 的方法(从 selenium 框架借用,:)),在 JNA 的帮助下,这也可以在 Windows 上完成(使用本机 Windows API 调用)。
为此(对于 Windows),您首先必须在以下位置获取 JNA 库:JAVA NATIVE ACCESS (JNA):下载 https://github.com/java-native-access/jna/releases或者从maven https://mvnrepository.com/artifact/net.java.dev.jna/jna
看下面的代码,它将获取一个(在本例中为 Windows)程序的 pid(大部分代码实际上是让 java 程序运行的碎片):
import com.sun.jna.*;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
static interface Kernel32 extends Library {
public static Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
public int GetProcessId(Long hProcess);
}
public static void main(String[] args) {
try {
Process p;
if (Platform.isWindows())
p = Runtime.getRuntime().exec("cmd /C ping msn.de");
else if (Platform.isLinux())
p = Runtime.getRuntime().exec("cmd /C ping msn.de");
System.out.println("The PID: " + getPid(p));
int x = p.waitFor();
System.out.println("Exit with exitcode: " + x);
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static int getPid(Process p) {
Field f;
if (Platform.isWindows()) {
try {
f = p.getClass().getDeclaredField("handle");
f.setAccessible(true);
int pid = Kernel32.INSTANCE.GetProcessId((Long) f.get(p));
return pid;
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (Platform.isLinux()) {
try {
f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
int pid = (Integer) f.get(p);
return pid;
} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{}
return 0;
}
}
希望这可以帮助, ;)...