在Java 6中使用继承的stdin / stdout / stderr启动进程

问题描述:

如果我通过Java的 ProcessBuilder >启动流程a> class,我可以完全访问该进程的标准输入,标准输出和标准错误流,如Java InputStreams OutputStreams 。但是,我找不到将这些流无缝连接到 System.in System.out 的方法,以及 System.err

If I start a process via Java's ProcessBuilder class, I have full access to that process's standard in, standard out, and standard error streams as Java InputStreams and OutputStreams. However, I can't find a way to seamlessly connect those streams to System.in, System.out, and System.err.

可以使用 redirectErrorStream()得到一个包含子进程标准输出和标准错误的 InputStream ,然后循环遍历并通过我的标准输出 - 但我找不到如果我使用C system()调用,就可以让用户输入进程,并且让用户键入进程。

It's possible to use redirectErrorStream() to get a single InputStream that contains the subprocess's standard out and standard error, and just loop through that and send it through my standard out—but I can't find a way to do that and let the user type into the process, as he or she could if I used the C system() call.

这在Java SE 7出现时似乎是可能的 - 我只是想知道现在是否有解决方法。如果 isatty()$ c的结果,则奖励积分子进程中的$ c> 进行重定向。

This appears to be possible in Java SE 7 when it comes out—I'm just wondering if there's a workaround now. Bonus points if the result of isatty() in the child process carries through the redirection.

您需要复制处理输出,错误和输入流到系统版本。最简单的方法是使用 IOUtils 类。 复制方法看起来就像你需要的那样。复制方法调用需要在单独的线程中。

You will need to copy the Process out, err, and input streams to the System versions. The easiest way to do that is using the IOUtils class from the Commons IO package. The copy method looks to be what you need. The copy method invocations will need to be in separate threads.

以下是基本代码:

// Assume you already have a processBuilder all configured and ready to go
final Process process = processBuilder.start();
new Thread(new Runnable() {public void run() {
  IOUtils.copy(process.getOutputStream(), System.out);
} } ).start();
new Thread(new Runnable() {public void run() {
  IOUtils.copy(process.getErrorStream(), System.err);
} } ).start();
new Thread(new Runnable() {public void run() {
  IOUtils.copy(System.in, process.getInputStream());
} } ).start();