运行子进程,在Java中正确地提供输入和输出

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

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

解决方法

您需要复制子进程的流和系统流(system.in,System.out和System.err)之间的输入和输出.这与 my recent quesion有关.到目前为止,我找到的最佳解决方案是:
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,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(),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之后,你再也无法读取它了.我目前使用的解决方法是使用单个输入重定向线程用于所有子进程.

相关文章

应用场景 C端用户提交工单、工单创建完成之后、会发布一条工...
线程类,设置有一个公共资源 package cn.org.chris.concurre...
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量