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");

}

}

}

}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章