4

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(); } } } 

1 Answer 1

5

The Process.destroy() method forcibly destroys an external process ... if this is possible. (In some situations you can't destroy processes, but that's only marginally relevant.)

Sign up to request clarification or add additional context in comments.

3 Comments

For example rt.exec("skynet") will probably ignore the Process.destroy() call.
Do you mean in my case I cannot destroy the process?
@sheng - not necessarily. All we are saying is that it is a possibility. For instance, if your application runs a setuid-root process on Linux/UNIX and it doesn't have root privilege, it won't be able to kill / destroy it. (There is probably an equivalent situation in Windows.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.