简体   繁体   中英

Calling external program in java with timeout

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM