How to add a timeout value when using Java's Runtime.exec()?

前端 未结 17 1857
长发绾君心
长发绾君心 2020-11-27 12:08

I have a method I am using to execute a command on the local host. I\'d like to add a timeout parameter to the method so that if the command being called doesn\'t finish in

17条回答
  •  猫巷女王i
    2020-11-27 12:30

    You can launch a Thread that sleeps for the time you want and after the sleep changing a boolean that you loop on in your executeCommandLine method.

    Something like that (not tested nor compiled, this solution is a prototype you should refactor it if it suit you needs):

    public static int executeCommandLine(final String commandLine,
                                         final boolean printOutput,
                                         final boolean printError)
        throws IOException, InterruptedException
    {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(commandLine);
    
        if (printOutput)
        {
            BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            System.out.println("Output:  " + outputReader.readLine());
        }
    
        if (printError)
        {
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            System.out.println("Error:  " + errorReader.readLine());
        }
    
        ret = -1;
        final[] b = {true};
        new Thread(){
           public void run(){
               Thread.sleep(2000); //to adapt
               b[0] = false;
           }
        }.start();
        while(b[0])
        {
              ret = process.waitFor();
        }
    
        return ret;
    }
    

提交回复
热议问题