I wrote the code below. To run a bat file from Java app, I use a process.exec(). But the bat may hang sometime, so I need to set a timeout for this process. I start a new thread and new a process in the thread, I set a timeout in the thread, and kill the thread when it is timeout. But I found that the process couldn't be destroyed when timeout happens. So I am confused about how to kill the porcess?
The code:
StreamGobbler:
import java.util.*; import java.io.*; class StreamGobbler extends Thread { InputStream is; String type; StreamGobbler(InputStream is, String type) { this.is = is; this.type = type; } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line=null; while ( (line = br.readLine()) != null) System.out.println(type + ">" + line); } catch (IOException ioe) { ioe.printStackTrace(); } } } Main:
public class test { public static void main(String args[]) throws InterruptedException { Runnable r = new ShengThread(); Thread sheng = new Thread(r); sheng.start(); sheng.join(1000); if (sheng.isAlive()) { sheng.interrupt(); } if (sheng.isAlive()) { System.out.println("It is dead."); } } } class ShengThread implements Runnable { public void run() { Process proc = null; try { String osName = System.getProperty("os.name" ); String[] cmd = new String[3]; if( osName.equals( "Windows XP" ) ) { cmd[0] = "cmd" ; cmd[1] = "/C" ; cmd[2] = "c:\\status.bat"; } Runtime rt = Runtime.getRuntime(); System.out.println(osName+"Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]); try { proc = rt.exec(cmd); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // any error message? StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // any output? StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // kick them off errorGobbler.start(); outputGobbler.start(); // any error??? int exitVal = proc.waitFor(); System.out.println("ExitValue: " + exitVal); } catch (InterruptedException t) { System.out.println("start\n"); proc.destroy(); t.printStackTrace(); } } }