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

前端 未结 17 1782
长发绾君心
长发绾君心 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条回答
  •  自闭症患者
    2020-11-27 12:21

    A light-weight solution for small apps:

    public class Test {
        public static void main(String[] args) throws java.io.IOException, InterruptedException {   
            Process process = new ProcessBuilder().command("sleep", "10").start();
    
            int i=0;
            boolean deadYet = false;
            do {
                Thread.sleep(1000);
                try {
                    process.exitValue();
                    deadYet = true;
                } catch (IllegalThreadStateException e) {
                    System.out.println("Not done yet...");
                    if (++i >= 5) throw new RuntimeException("timeout");
                }
            } while (!deadYet);
        }
    }
    

提交回复
热议问题