9

在 Windows 下,当我的程序从命令行启动时,我无法可靠地操作子进程的 I/O。令人沮丧的是,服务器使用控制台进行 I/O 是标准的。GUI 很好,但我真的更喜欢坚持使用命令行并保持简单。我注意到当我从 Eclipse IDE 执行服务器时,子进程 I/O 很好,但从命令行运行则完全不同。我无法读取或写入子进程,但该进程仍在运行。我在下面编写了一些测试代码来演示这个问题,我希望这个问题可以在另一台机器上重现,然后希望从中得到解决方案。从 Eclipse 执行时,继承的 I/O 会按预期工作。然而,当从 Windows 命令提示符执行时,没有任何内容可以读取或写入子进程。在这两种情况下,将子进程输出重定向到文件总是成功,但输入仍然无法传递给子进程。如果已经有解决此问题的方法,请链接该页面。

JRE/JDK 实现:

>java -version
java version "1.7.0_01"
Java(TM) SE Runtime Environment (build 1.7.0_01-b08)
Java HotSpot(TM) 64-Bit Server VM (build 21.1-b02, mixed mode)

考虑以下代码:

package com.comp8nerd4u2.io.test;

/*
 * These tests attempt to confirm what I'm experiencing under my build environment
 */

import java.io.File;
import java.io.IOException;

public final class PIOTest {

/** The command to run as a child process. The command itself isn't the test, but what you use to run this Java program is the test. */
private static final String[] COMMAND = {"cmd.exe", "/c", "echo This is a test. Feel free to change this."}; // Change this to just {"cmd.exe"} or some other program that accepts input and you'll see how frustrating this is
/** Controls how the test process is built */
private static final ProcessBuilder PB = new ProcessBuilder(COMMAND);
/** How long to allow the process to run before forcibly terminating it. */
private static final long PROCESS_TIMEOUT = 10000L;
private static final Runnable R = new TimedInterruptWorker(PROCESS_TIMEOUT);

private static int n = 0;

static {
    PB.redirectErrorStream(true);
}

private PIOTest() {}

public static void main(String[] args) {

    // ----- Begin Tests -----

    /*
     * Test #1: Let's test putting our command's output onto our standard I/O streams
     * Goal condition: Child process outputs expected output, and exits before the timeout. If child process expects input, it should accept entered input.
     * Known success factors: Parent process' standard I/O is piped to Eclipse. Tests would probably succeed with Netbeans as well
     * Known fail factors: Parent process' standard I/O is piped to Windows Command Prompt
     * Result under fail condition: Child process hangs if it fills up its output buffer or requests input, but exits on its own otherwise, unless it took longer than the timeout. 
     */
    PB.inheritIO();
    doTest();

    // Test #2: Let's test putting our command's output into a file
    PB.redirectOutput(new File("piotest.txt"));
    doTest();
}

/**
 * Performs the I/O test.
 */
private static void doTest() {
    n++;
    Process p = null;
    try {
        p = PB.start();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    try {
        Thread t = new Thread(R);
        t.setDaemon(true);
        t.start();
        System.out.format("[Test #%d] Child exited with status code %d\n", n, p.waitFor());
        t.interrupt();
    } catch (InterruptedException e) {
        p.destroy();
        System.out.format("[Test #%d] Child took longer than the timeout.\n", n);
    }
}

/**
 * Useful for sending interrupts after a certain amount of time has passed.
 * 
 * @author comp8nerd4u2
 */
private static final class TimedInterruptWorker implements Runnable {

    private long timeout = 0;
    private Thread target = null;

    public TimedInterruptWorker(long timeout) {
        this(timeout, Thread.currentThread());
    }

    public TimedInterruptWorker(long timeout, Thread target) {
        this.timeout = timeout;
        this.target = target;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
            return;
        }
        target.interrupt();
    }

}

}

更新:我修改了测试以在运行时接受任何命令,并将其上传到我的 linux vps 服务器。我从 ssh 会话运行它,所有子进程的 I/O 都可以轻松读取和写入。我注意到了一件事。当我打开一个交互式 bash shell 作为子进程,然后将它的输出重定向到一个文件时,我想 CentOS 停止了我的程序。那或我的程序崩溃了。

[admin@comp8nerd4u2 piotest]$ java -jar piotest.jar
Enter command to run : bash
[admin@comp8nerd4u2 piotest]$ [Test #1] Child took longer than the timeout.

[1]+  Stopped                 java -jar piotest.jar
[admin@comp8nerd4u2 piotest]$

第一行是我输入的命令。第二行是生成的 bash shell,但我从未在其中输入任何内容,因此我的程序在超时后将其杀死。它为第二次测试做好准备,创建“piotest.txt”文件,然后崩溃或被操作系统停止。实际测试本身没有改变,只是测试现在允许您输入在运行时运行的命令。这在linux中可以正常工作,但在windows中不行。我希望知道 Win32 API 的人能以某种方式解释为什么这个测试在 Windows 中失败。

4

2 回答 2

2

你看过这篇文章吗?http://www.javaworld.com/jw-12-2000/jw-1229-traps.html?page=1

在我看来,您需要为 Windows 上的输入/输出流提供服务。这篇文章是关于 Runtime.exec,但我敢打赌 ProcessBuilder 的本机代码非常相似,并且在 Windows 上具有相同类型的问题。

我猜测为什么这在 Windows 上的 Eclipse 上有效,是 Eclipse 代表您为流提供服务,以便在控制台视图中显示内容。

于 2012-06-24T17:31:15.953 回答
1

我知道我回答迟了,但在找到答案之前我遇到了这个问题,并且想在同一条船上拯救其他人一些搜索。

这实际上是 Windows 的一个已知错误:https ://bugs.openjdk.java.net/browse/JDK-8023130

您可以通过自己重定向流来解决它:

Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
   System.out.println(line);
}

p.waitFor();

br.close();
于 2014-02-11T23:16:05.287 回答