java 关闭子进程吗_强制杀死子进程的Java工具/方法

小编典典

使用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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值