获取BufferedReader.readLine()等待输入

Get BufferedReader.readLine() to wait for input

我有一个 Python 服务器,我从 Java ProcessBuilder 线程开始。 Java 程序应等到服务器准备就绪后再继续。当服务器准备就绪时,它会输出一条 "Server-ready" 消息,我假设它是由 Process 对象的 InputStream 接收的。

START_SERVER_COMMAND = TAGGERFLOW_HOME + "server.py";
server = new ProcessBuilder().inheritIO().command("python", START_SERVER_COMMAND, "" + portNum,
        config.featOrderName(), config.childOrderName(), "" + maxBeta).start();
System.out.println("Hypertagger server started");
LOGGER.log(Level.INFO, "Hypertagger server started");

String line = null;
while(line == null) {
    line = new BufferedReader(new InputStreamReader(server.getInputStream())).readLine();
    if(line == null)
        Thread.sleep(5000);
}
System.out.println("Exit loop");

但是,line 始终为 null,因此 Java 永远不会退出循环。这很可能表明我关于 InputStream 接收 "Server-ready" 消息的假设是错误的,但我不知道为什么会这样。

我正在寻找获取 "Server-ready" 消息的方法或检测服务器何时准备就绪的更好方法。任何帮助将不胜感激。

编辑

在此之前,我尝试在循环之前初始化 BufferedReader。它有相同的行为。

TL;DR: 如果您希望 Java 程序捕获输出,请不要将输出重定向到其他地方,即不要调用 inheritIO(),虽然你可能想调用 redirectErrorStream(true).


你认为 inheritIO() 有什么作用?

Sets the source and destination for subprocess standard I/O to be the same as those of the current Java process.

This is a convenience method. An invocation of the form

pb.inheritIO()

behaves in exactly the same way as the invocation

pb.redirectInput(Redirect.INHERIT)
  .redirectOutput(Redirect.INHERIT)
  .redirectError(Redirect.INHERIT)

当 I/O 被重定向时,您认为 getInputStream() 做了什么?

Returns the input stream connected to the normal output of the subprocess. The stream obtains data piped from the standard output of the process represented by this Process object.

If the standard output of the subprocess has been redirected using ProcessBuilder.redirectOutput then this method will return a null input stream.

应该很明显,但是什么是空输入流

a destination for standard output and standard error. By default, the subprocess writes standard output and standard error to pipes. Java code can access these pipes via the input streams returned by Process.getInputStream() and Process.getErrorStream(). However, standard output and standard error may be redirected to other destinations using redirectOutput and redirectError. In this case, Process.getInputStream() and/or Process.getErrorStream() will return a null input stream, for which:

  • the read methods always return -1
  • the available method always returns 0
  • the close method does nothing