java中建立進程

Java中提供了兩種方法來啓動其它進程:
方法一:
    Process process = new ProcessBuilder(cmd).start();
方法二:
    Process process = Runtime.getRuntime().exec(cmd);
    注意:底層也是調用方法一。緩存


Process的waitFor()方法:
    說明:等待Process結束後返回Process的返回值,若Process一直未結束,則程序一直等待下去。
    分析:
        建立的新進程與jvm創建三個管道鏈接:標準輸入流、標準輸出流、標準錯誤輸出流。
        若新進程不斷向標準輸入流、標準錯誤輸出流寫數據,而jvm不讀取的話,則會致使緩衝區塞滿而沒法繼續寫數據,從而形成新進程一直不結束,最終致使調用waitFor()方法的線程阻塞。
    解決:
        jvm讀取新進程寫入緩存區的數據(即:標準輸入流Process.getInputStream()、標準錯誤輸出流Process.getErrorStream()中的數據)便可。
        eg:
                // 打印進程的輸出信息
                List<String> outputStr = IOUtils.readLines(process.getInputStream(), "UTF-8");
                List<String> errorOutputStr = IOUtils.readLines(process.getErrorStream(), "UTF-8");
                LOGGER.info("=============new process output start =======");
                LOGGER.info(outputStr.toString());
                LOGGER.info("=============new process output end =======");
                LOGGER.info("=============new process error output start =======");
                LOGGER.info(errorOutputStr.toString());
                LOGGER.info("=============new process error output end =======");jvm

    相關源碼:
        /**
         * Causes the current thread to wait, if necessary, until the process represented by this {@code Process} object has terminated.  
         * This method returns immediately if the subprocess has already terminated.  
         * If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
         */
        public synchronized int waitFor() throws InterruptedException {
            while (!hasExited) {
                wait();
            }
            return exitcode;
        }ui


        /**
         * Returns the input stream connected to the normal output of the subprocess.  
         * The stream obtains data piped from the standard output of the process represented by this {@code Process} object.
         */
        public abstract InputStream getInputStream();this


        /**
         * Returns the input stream connected to the error output of the subprocess. 
         * The stream obtains data piped from the error output of the process represented by this {@code Process} object.
         */
        public abstract InputStream getErrorStream();.net


        /**
         * Returns the output stream connected to the normal input of the subprocess.  
         * Output to the stream is piped into the standard input of the process represented by this {@code Process} object.
         */
        public abstract OutputStream getOutputStream();線程

相關文章
相關標籤/搜索