0

I am facing an issue calling an external program from java with timeout. I got the below code. This program tries to open notepad.exe through java and terminates after 5 seconds. The problem I am facing is that although its terminating the notepad, the java process still remains active (eclipse does not terminate). Experts please help!

public class ExecTest {

public static void main(String[] args) {
    System.out.println("STARTING");
    new ExecTest().callNotepad();
    System.out.println("ENDING");
}

public ExecTest() {
}

private void callNotepad() {
    ProcessBuilder pb = new ProcessBuilder("notepad.exe");
    pb.redirectErrorStream(true);
    try {
        Timer t = new Timer();
        pb.redirectErrorStream(true);
        Process p = pb.start();
        TimerTask killer = new TimeoutProcessKiller(p);
        t.schedule(killer, 5000);
        try {
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = "";
            while ((line = br.readLine()) != null) {
                System.out.println(line + "\n");
            }
            p.waitFor();
            System.out.println("HERE!");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            System.out.println("Cancelling timer");
            killer.cancel();
            System.out.println("Cancelled timer");
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

class TimeoutProcessKiller extends TimerTask {
private Process p;
public TimeoutProcessKiller(Process p) {
    this.p = p;
}

@Override
public void run() {
    System.out.println("Destroying thread p=" + p);
    p.destroy();
    System.out.println("Destroyed thread p=" + p);
}

}

1 Answer 1

2

You have cancelled the TimerTask killer instead of the Timer t.
Just exchange killer.cancel(); with t.cancel()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.