2015-04-28 69 views
1

我试图让程序运行一些可执行程序(称为p),给定时间限制t毫秒。它执行以下任务:从具有时间限制的程序执行程序(Java)

  1. 如果程序p已正常执行,则将其输出到控制台。
  2. 如果程序p无法在时间限制内完全执行,请打印"Sorry, needs more time!",然后终止执行p
  3. 如果程序p异常终止(例如RuntimeError),打印"Can I've some debugger?"

我使用ProcessResultReader类在下面的程序从here。我的程序正在工作,只要p完成正常执行或终止异常。但是,如果p本身在timeout之后没有终止,则它不终止(尝试p并且没有退出条件的简单while(true)循环)。看起来线程stdout即使在执行stdout.stop()后仍然存在。我在这段代码中做错了什么?

谢谢。

import java.util.concurrent.TimeUnit; 
import java.io.*; 

class ProcessResultReader extends Thread 
{ 

    final InputStream is; 
    final StringBuilder sb; 

    ProcessResultReader(final InputStream is) 
    { 
     this.is = is; 
     this.sb = new StringBuilder(); 
    } 
    public void run() 
    { 
     try 
     { 
      final InputStreamReader isr = new InputStreamReader(is); 
      final BufferedReader br = new BufferedReader(isr); 
      String line = null; 
      while ((line = br.readLine()) != null) 
      { 
       this.sb.append(line).append("\n"); 
      } 
     } 
     catch (final IOException ioe) 
     { 
      System.err.println(ioe.getMessage()); 
      throw new RuntimeException(ioe); 
     } 
    } 

    @Override 
    public String toString() 
    { 
     return this.sb.toString(); 
    } 
    public static void main(String[] args) throws Exception 
    { 
     int t = 1000; 
     Process p = Runtime.getRuntime().exec(cmd); //cmd is command to execute program p 
     ProcessResultReader stdout = new ProcessResultReader(p.getInputStream()); 
     stdout.start(); 
     if(!p.waitFor(t, TimeUnit.MILLISECONDS)) 
     { 
      stdout.stop(); 
      p.destroy(); 
      System.out.println("Sorry, needs more time!"); 
     } 
     else 
     { 
      if(p.exitValue()==0) System.out.println(stdout.toString()); 
      else System.out.println("Can I've some debugger?"); 
     } 
    } 
} 
+1

我知道[this](http://stackoverflow.com/a/2733370/1858327)不完全是你要找的,但它似乎可以帮助或至少指出你在正确的方向。 –

回答

0

根据Java文档, stdout.stop()已被废弃,甚至stdout.destroy()永远不会实现。

有关详细信息,请参阅为何Thread.stop,Thread.suspend and Thread.resume Deprecated?.

可以转而尝试。

String cmd="cmd /c sleep 5"; 
    int timeout = 1; 
    Process p = Runtime.getRuntime().exec(cmd); //cmd is command to execute program p 
    ProcessResultReader stdout = new ProcessResultReader(p.getInputStream()); 
    stdout.start(); 
    if(!p.waitFor(timeout, TimeUnit.MILLISECONDS)) 
    { 
     stdout.stop(); 
     p.destroy(); 
     System.out.println("Sorry, needs more time!"); 
     System.out.flush(); 
    } 
    else 
    { 
     if(p.exitValue()==0) System.out.println(stdout.toString()); 
     else System.out.println("Can I've some debugger?"); 
    } 
+0

我知道'stop()'已弃用。请注意,我想在超时发生时终止执行'p',而不是主要的。否则,我会用'System.exit'。 – user148865