2010-04-24 29 views
3

我不知道爲什麼這是懸掛。我試圖從通過commons-exec運行的進程捕獲輸出,並且我繼續掛起。我提供了一個示例程序來演示下面的這種行爲。commons-exec:當我調用executor.execute(commandLine)時掛起;

import java.io.DataInputStream; 
import java.io.IOException; 
import java.io.PipedInputStream; 
import java.io.PipedOutputStream; 
import org.apache.commons.exec.CommandLine; 
import org.apache.commons.exec.DefaultExecutor; 
import org.apache.commons.exec.ExecuteException; 
import org.apache.commons.exec.PumpStreamHandler; 
public class test { 

public static void main(String[] args) { 
    String command = "java"; 

    PipedOutputStream output = new PipedOutputStream(); 
    PumpStreamHandler psh = new PumpStreamHandler(output); 

    CommandLine cl = CommandLine.parse(command); 

    DefaultExecutor exec = new DefaultExecutor(); 
    DataInputStream is = null; 
    try { 
     is = new DataInputStream(new PipedInputStream(output)); 
     exec.setStreamHandler(psh); 
     exec.execute(cl); 
    } catch (ExecuteException ex) { 
    } catch (IOException ex) { 
    } 

    System.out.println("huh?"); 
} 
} 

回答

9

按照javadocexecute(CommandLine command)是同步的,execute(CommandLine command, ExecuteResultHandler handler)另一方面是異步的。

5

您調用的命令java產生輸出到其標準輸出流。該流必須通過調用程序輸入到輸入流中。這在您的程序中不會發生。

您必須在單獨的線程中讀取輸入流(代碼中的is),因爲這是管道流的工作方式。請注意,在致電​​之前,您必須啓動讀取線程。

Capturing large amounts of output from Apache Commons-Exec

看到根據Streaming output with commons-exec?你期望的大數據您的其他問題,所以你必須使用管道流而不能使用使用ByteArrayInputStream作爲輸出的簡單的方法。你在那裏給自己的答案,與你的代碼在這裏遇到同樣的問題。

相關問題