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

标签 java process runtime.exec

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

我使用 StreamGobbler 来显示使用 process.getInputStream() 的程序输出。但是,我不知道如何识别程序何时等待输入以及何时使用 proc.getOutputStream 为其提供输入。我该怎么做?

最佳答案

您需要在子进程的流和 System 流之间复制输入和输出(System.inSystem.outSystem.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, 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 中提取一个 channel 。否则,您将无法在子进程终止时中断读取输入的线程。

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

关于java - 运行子进程,在 Java 中正确地为其提供输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4272956/

相关文章:

node.js - Nodejs 读取某些进程的标准输出并执行操作

java - Java/ColdFusion 和 Lucee 之间的 identityHashCode 区别

java - 线程中出现异常 "main"java.lang.UnsatisfiedLinkError : no jniopencv_core in java. library.path

c - 一个进程中放置多少个线程

java - Java中编译C的时间间隔定义

java - 使用 Runtime#exec() 编译和执行 Java 代码

Android-执行 Runtime.getRuntime().exec() 时出错 - 环境为空 -ffmpeg

java:运行时相当于数字类型之间的转换

java - java中解决时间冲突的最佳方法是什么?

c - 如何在c中使用execl命令创建文件