【问题标题】:commons-exec: hanging when I call executor.execute(commandLine);commons-exec:当我调用 executor.execute(commandLine); 时挂起
【发布时间】:2010-04-24 01:25:36
【问题描述】:

我不知道为什么会挂起。我正在尝试从通过 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?");
}
}

【问题讨论】:

    标签: java multithreading apache-commons-exec


    【解决方案1】:

    根据javadocexecute(CommandLine command) 是同步的,而execute(CommandLine command, ExecuteResultHandler handler) 是异步的。

    【讨论】:

      【解决方案2】:

      您调用的命令java 将输出生成到其标准输出流。该流必须由您的调用程序泵入输入流。这不会在您的程序中发生。

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

      另见Capturing large amounts of output from Apache Commons-Exec

      根据您的另一个问题Streaming output with commons-exec?,您需要大量数据,因此您必须使用管道流,并且不能使用使用ByteArrayInputStream 作为输出的更简单方法。您在此处给自己的答案与此处的代码存在相同的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-15
        • 1970-01-01
        • 2012-03-31
        • 1970-01-01
        • 1970-01-01
        • 2023-04-11
        • 1970-01-01
        相关资源
        最近更新 更多