Wait for process to finish before proceeding in Java

后端 未结 4 1299
無奈伤痛
無奈伤痛 2020-12-01 18:24

Essentially, I\'m making a small program that\'s going to install some software, and then run some basic commands afterwards to prep that program. However, what is happening

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 19:16

    If you are running a system command that returns a very long response string, stdin buffer fills up and the process appears to hang. This happened to me with sqlldr. If that appears to be the case then just read from stdin as the process is running.

        try {
            ProcessBuilder pb = new ProcessBuilder("myCommand");
            Process p = pb.start();
            BufferedReader stdInput = new BufferedReader(new 
                    InputStreamReader(p.getInputStream()));
    
            BufferedReader stdError = new BufferedReader(new 
                    InputStreamReader(p.getErrorStream()));
            StringBuffer response = new StringBuffer();
            StringBuffer errorStr = new StringBuffer();
            boolean alreadyWaited = false;
            while (p.isAlive()) {
                try {
                    if(alreadyWaited) {
    
                        // read the output from the command because
                        //if we don't then the buffers fill up and
                        //the command stops and doesn't return
                        String temp;
    
                        while ((temp = stdInput.readLine()) != null) {
                            response.append(temp);
                        }
    
    
                        String errTemp;
                        while ((errTemp = stdError.readLine()) != null) {
                            errorStr.append(errTemp);
                        }                                                   
                    }
                    Thread.sleep(1000);
                    alreadyWaited = true;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                logger.debug("Response is " + response);
                logger.debug("Error is: " + errorStr);
            }
    
        } catch (IOException e) {
            logger.error("Error running system command", e);
        }
    

提交回复
热议问题