小编典典
使用Java JNA可以找到一种更精简的方法。
这绝对适用于Windows和Linux,我认为您也可以在其他平台上执行相同的操作。
Java进程处理的最大问题是缺少一种方法来获取以untime.getRuntime()。exec()开始的进程的进程ID。
假设您已获得进程的pid,则始终可以在linux中启动kill -9命令,或使用类似的方法在Windows中终止进程。
这是一种本地获取linux进程ID的方法(从selenium框架中借来的:)),借助JNA,也可以在Windows上完成此操作(使用本地Windows
API调用)。
为此(对于Windows),必须首先从JAVA NATIVE ACCESS(JNA)获得JNA库:下载或从maven获取它。
查看以下代码,该代码将获取(在此示例中为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;
}
}
希望这可以帮助, ;)…
2020-09-15