Java 程序中启动及关闭命令行程序



Java 程序中启动及关闭命令行程序

我需要在java中启动一个用C++编写的命令行程序.。用 Runtime.getRuntime().exec("c://example.exe"); 没有成功。

后来找到启动命令行程序的方法


Process process = Runtime.getRuntime().exec("cmd.exe /c start c://example.exe");

可是发现调用 process.destroy() 方法并无法结束用上述方法启动的程序。请问这是怎么原因?

我自己找到了一种方法结束它。在windows中,调用 tasklist 命令找到该程序的 pid 然后调用 taskkill 方法结束进程。


String programName = "example.exe";

Process process = Runtime.getRuntime().exec("cmd.exe /c start c://" + programName);


Thread.sleep(2000);


Process listprocess = Runtime.getRuntime().exec("cmd.exe /c tasklist");

InputStream is = listprocess.getInputStream();

byte[] buf = new byte[256];

BufferedReader r = new BufferedReader(new InputStreamReader(is));


StringBuffer sb = new StringBuffer();

String str = null;

while ((str = r.readLine()) != null) {

String id = null;

Matcher matcher = Pattern.compile(programName + "[ ]*([0-9]*)").matcher(str);

while (matcher.find()) {

if (matcher.groupCount() >= 1) {

id = matcher.group(1);

if (id != null) {

Integer pid = null;

try {

pid = Integer.parseInt(id);

} catch (NumberFormatException e) {

e.printStackTrace();

}

if (pid != null) {

Runtime.getRuntime().exec("cmd.exe /c taskkill /f /pid " + pid);

System.out.println("kill progress");

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值