commons-exec:当我调用executor.execute(commandLine)时挂起;

Ste*_*all 3 java multithreading apache-commons-exec

我不知道为什么会这样.我试图通过commons-exec捕获进程的输出,然后我继续挂起.我已经提供了一个示例程序来演示以下这种行为.

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?");
}
}
Run Code Online (Sandbox Code Playgroud)

Gui*_*ume 9

根据javadoc,execute(CommandLine command)是同步的,execute(CommandLine command, ExecuteResultHandler handler)另一方面是异步的.


Chr*_*rau 5

您调用的命令会将java输出生成到其标准输出流.必须通过调用程序将该流抽入输入流.这不会发生在你的程序中.

您必须is在单独的线程中读取输入流(在您的代码中),因为这是管道流的工作方式.请注意,您必须在调用之前启动读取线程execute().

另请参阅从Apache Commons-Exec捕获大量输出

根据你的另一个问题用commons-exec输出流量?你期望大数据,所以你必须使用管道流,不能使用更简单的方法使用ByteArrayInputStream输出.你在那里给自己的答案,遇到与你的代码相同的问题.