[英]Calling external program in java with timeout
我面臨一個問題,從Java調用帶有超時的外部程序。 我得到了下面的代碼。 該程序嘗試通過Java打開notepad.exe,並在5秒鍾后終止。 我面臨的問題是,盡管它終止了記事本,但Java進程仍然保持活動狀態(eclipse不會終止)。 高手請幫忙!
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);
}
}
您取消了TimerTask killer
而不是Timer t
。
只需交換killer.cancel();
用t.cancel()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.