8

我使用 Runtime exec() 方法在 Java 中创建子进程。但是,由于子流程是一个交互式程序,我需要在需要时为其提供输入。我还需要显示子流程的输出。我怎样才能以最简单的方式做到这一点?

我正在使用 StreamGobbler 使用 process.getInputStream() 显示程序输出。但是,我不知道如何识别程序何时等待输入以及何时使用 proc.getOutputStream 为其提供输入。我怎样才能做到这一点?

4

2 回答 2

3

您需要在子流程的流和System流(System.inSystem.out)之间复制输入和输出System.err。这与我最近的问题有关。到目前为止,我发现的最佳解决方案是:

import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.FileChannel;

class StreamCopier implements Runnable {
    private InputStream in;
    private OutputStream out;

    public StreamCopier(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

    public void run() {
        try {
            int n;
            byte[] buffer = new byte[4096];
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
                out.flush();
            }
        }
        catch (IOException e) {
            System.out.println(e);
        }
    }
}

class InputCopier implements Runnable {
    private FileChannel in;
    private OutputStream out;

    public InputCopier(FileChannel in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

    public void run() {
        try {
            int n;
            ByteBuffer buffer = ByteBuffer.allocate(4096);
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer.array(), 0, n);
                out.flush();
            }
            out.close();
        }
        catch (AsynchronousCloseException e) {}
        catch (IOException e) {
            System.out.println(e);
        }
    }
}

public class Test {
    private static FileChannel getChannel(InputStream in)
            throws NoSuchFieldException, IllegalAccessException {
        Field f = FilterInputStream.class.getDeclaredField("in");
        f.setAccessible(true);
        while (in instanceof FilterInputStream)
            in = (InputStream)f.get((FilterInputStream)in);
        return ((FileInputStream)in).getChannel();
    }

    public static void main(String[] args)
            throws IOException, InterruptedException,
                   NoSuchFieldException, IllegalAccessException {
        Process process = Runtime.getRuntime().exec("sh -i +m");
        Thread outThread = new Thread(new StreamCopier(
                process.getInputStream(), System.out));
        outThread.start();
        Thread errThread = new Thread(new StreamCopier(
                process.getErrorStream(), System.err));
        errThread.start();
        Thread inThread = new Thread(new InputCopier(
                getChannel(System.in), process.getOutputStream()));
        inThread.start();
        process.waitFor();
        System.in.close();
        outThread.join();
        errThread.join();
        inThread.join();
    }
}

这里棘手的部分是从System.in. 如果没有这个,您将无法在子进程终止时中断读取输入的线程。

这种方法有一个严重的缺点:关闭后System.in您无法再从中读取。我目前使用的解决方法是让一个输入重定向线程用于所有子进程。

于 2010-11-25T07:17:16.230 回答
3

问问自己“当我从命令行运行程序时,我如何知道程序何时需要输入”?您会看到它的提示并根据该提示输入数据。原理是一样的,只是您的代码需要解释程序的输出并提供正确的输入。

为避免重新发明轮子,请查看ExpectJ和/或Expect4J,它们是古老的 *nix Expect工具的 Java 实现,旨在处理这种编程交互。

于 2010-11-25T04:29:28.370 回答