Java - 如果数据太小,刷新进程的 OutputStream 不会立即发送数据

voi*_*tar 5 java outputstream

我正在从Java启动一个外部进程,并通过等方式获取它的stdin、stdout和stderr。我的问题是:当我想将数据写入我的输出流(过程的stdin)时,直到我实际调用它process.getInputStream()时,它才会被发送。close()溪流。我明确地打电话flush()

我做了一些实验,发现如果我增加发送的字节数,它最终会通过。在我的系统上,神奇数字是4058字节。

为了测试,我将数据发送到 perl 脚本,其内容如下:

#!/usr/bin/perl
use strict;
use warnings;

print "Perl starting";

while(<STDIN>) {
    print "Perl here, printing this: $_" 
}
Run Code Online (Sandbox Code Playgroud)

现在,这是 java 代码:

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;

public class StreamsExecTest {


    private static String readInputStream(InputStream is) throws IOException {
        int guessSize = is.available();
        byte[] bytes = new byte[guessSize];
        is.read(bytes); // This call has side effect of filling the array
        String output = new String(bytes);
        return output;
    }

    public static void main(String[] args) {

        System.out.println("Starting up streams test!");

        ProcessBuilder pb;
        pb = new ProcessBuilder("./test.pl");


        // Run the proc and grab the streams
        try {
            Process p = pb.start();
            InputStream pStdOut = p.getInputStream();
            InputStream pStdErr = p.getErrorStream();
            OutputStream pStdIn = p.getOutputStream();


            int counter = 0;
            while (true) {  

                String output = readInputStream(pStdOut);
                if (!output.equals("")) {
                    System.out.println("<OUTPUT> " + output);
                }

                String errors = readInputStream(pStdErr);
                if (!errors.equals("")) {
                    System.out.println("<ERRORS> " + errors);
                }

                if (counter == 50) {
                    // Write to the stdin of the execed proc.  The \n should
                    // in turn trigger it to treat it as a line to process
                    System.out.println("About to send text to proc's stdin");
                    String message = "hello\n";

                    byte[] pInBytes = message.getBytes();
                    pStdIn.write(pInBytes);
                    pStdIn.flush();
                    System.out.println("Sent " + pInBytes.length + " bytes.");

                }

                if (counter == 100) {
                    break;
                }

                Thread.sleep(100);
                counter++;
            }
            // Cleanup
            pStdOut.close();
            pStdErr.close();
            pStdIn.close();
            p.destroy();

        } catch (Exception e) {
            // Catch everything
            System.out.println("Exception!");
            e.printStackTrace();
            System.exit(1);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

所以当我运行这个时,我实际上没有得到任何回报。如果在调用 后立即flush()调用close()pStdIn,它会按预期工作。但这不是我想要的;我希望能够持续保持流打开并在我高兴的时候写入它。如前所述,如果消息为 4058 字节或更大,则无需close().

操作系统(在 64 位 Linux 上运行,具有 64 位 Sun JDK 的价值)是否在发送数据之前缓冲数据?我可以看到 Java 对此没有真正的控制权,一旦 JVM 进行系统调用以写入管道,它所能做的就是等待。但还有另一个难题:

Perl 脚本在进入while循环之前打印行。由于我在 Java 循环的每次迭代中都会检查来自 Perl 的标准输出的任何输入,因此我希望在第一次运行循环时看到它,看到从 Java->Perl 发送数据的尝试,然后什么也没有。但实际上,当写入输出流时,我实际上只看到来自 Perl 的初始消息(在 OUTPUT 消息之后)。是否有我不知道的阻碍?

非常感谢任何帮助!

Jim*_*son 3

您还没有告诉 Perl 使用无缓冲的输出。查看perlvar并搜索$|设置无缓冲模式的不同方法。本质上,以下之一:

HANDLE->autoflush( EXPR )
$OUTPUT_AUTOFLUSH
$| 
Run Code Online (Sandbox Code Playgroud)