java native Process timeout

前端 未结 6 1469
不思量自难忘°
不思量自难忘° 2020-11-27 14:31

At the moment I execute a native process using the following:

java.lang.Process process = Runtime.getRuntime().exec(command); 
int returnCode = process.waitF         


        
6条回答
  •  天命终不由人
    2020-11-27 15:20

    What about the Groovy way

    public void yourMethod() {
        ...
        Process process = new ProcessBuilder(...).start(); 
        //wait 5 secs or kill the process
        waitForOrKill(process, TimeUnit.SECONDS.toMillis(5));
        ...
    }
    
    public static void waitForOrKill(Process self, long numberOfMillis) {
        ProcessRunner runnable = new ProcessRunner(self);
        Thread thread = new Thread(runnable);
        thread.start();
        runnable.waitForOrKill(numberOfMillis);
    }
    
    protected static class ProcessRunner implements Runnable {
        Process process;
        private boolean finished;
    
        public ProcessRunner(Process process) {
            this.process = process;
        }
    
        public void run() {
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                // Ignore
            }
            synchronized (this) {
                notifyAll();
                finished = true;
            }
        }
    
        public synchronized void waitForOrKill(long millis) {
            if (!finished) {
                try {
                    wait(millis);
                } catch (InterruptedException e) {
                    // Ignore
                }
                if (!finished) {
                    process.destroy();
                }
            }
        }
    }
    

提交回复
热议问题