繁体   English   中英

从具有时间限制的程序中执行程序(Java)

[英]Execution of Program from Program with Time Constraints (Java)

我正在尝试使程序在给定的时间限制为t ms的情况下运行一些可执行程序(称为p )。 它执行以下任务:

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

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

谢谢。

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

根据Java文档,stdout.stop()已被弃用,甚至stdout.destroy()也从未实现。

有关更多信息,请参见为什么不赞成使用 Thread.stop, Thread.suspend和Thread.resume?

您可以试试看。

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

暂无
暂无

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

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