简体   繁体   English

使用超时在Java中调用外部程序

[英]Calling external program in java with timeout

I am facing an issue calling an external program from java with timeout. 我面临一个问题,从Java调用带有超时的外部程序。 I got the below code. 我得到了下面的代码。 This program tries to open notepad.exe through java and terminates after 5 seconds. 该程序尝试通过Java打开notepad.exe,并在5秒钟后终止。 The problem I am facing is that although its terminating the notepad, the java process still remains active (eclipse does not terminate). 我面临的问题是,尽管它终止了记事本,但Java进程仍然保持活动状态(eclipse不会终止)。 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 . 您取消了TimerTask killer而不是Timer t
Just exchange killer.cancel(); 只需交换killer.cancel(); with t.cancel() t.cancel()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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