关闭CMD进程-JAVA

引自 http://blog.csdn.net/yzh_2017/article/details/70174478

问题:

使用destory方法无法关闭运行的CMD进程,所以需要换个方法,查出当前cmd进程PID,然后调用taskkill杀掉进程。


1.需要两个JAR包

jna.jar和platform.jar,导入工程;

2.代码如下:

private static void killProcessTree(Process process) {
		try {
			Field f = process.getClass().getDeclaredField("handle");
			f.setAccessible(true);
			long handl = f.getLong(process);
			Kernel32 kernel = Kernel32.INSTANCE;
			WinNT.HANDLE handle = new WinNT.HANDLE();
			handle.setPointer(Pointer.createConstant(handl));
			int ret = kernel.GetProcessId(handle);
			Long PID = Long.valueOf(ret);
			String cmd = getKillProcessTreeCmd(PID);
			Runtime rt = Runtime.getRuntime();
			Process killPrcess = rt.exec(cmd);
			killPrcess.waitFor();
			killPrcess.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getKillProcessTreeCmd(Long Pid) {
		String result = "";
		if (Pid != null)
			result = "cmd.exe /c taskkill /PID " + Pid + " /F /T ";
		return result;
	}


你可能感兴趣的:(Java,CMD)