简体   繁体   English

Windows上无缓冲的子进程标准输出

[英]Unbuffered subprocess stdout on windows

Is there an easy way to read output from subprocess unbuffered? 有没有一种简单的方法来读取子进程无缓冲的输出? I'm trying to call a C program from Java, but apparently it's stdout block-buffered when connected to pipe and line-buffered only when connected to console. 我正在尝试从Java调用一个C程序,但显然当连接到管道时它是stdout块缓冲,只有在连接到控制台时才进行行缓冲。 I cannot modify C program. 我无法修改C程序。

Maybe there is a way to fool the program into thinking it is connected to console? 也许有办法欺骗程序认为它连接到控制台? Bonus points for a solution that works on linux as well. 对于适用于Linux的解决方案的奖励积分。

这不是一个很好的解决方案,但运行时库可能不会缓冲串行端口,所以如果你非常绝望,你可以使用零调制解调器模拟器,如com0com或其衍生物。

您是否尝试过使用环境变量BUF_1_ = 0?

OK - 好 -

1) "Line buffered input" is a common idiom for console-mode programs, dating back to the original Unix and serial-mode VTxx terminals. 1)“行缓冲输入”是控制台模式程序的常用习惯用法,可追溯到原始Unix和串行模式VTxx终端。

2) You can read "raw, unbuffered" I/O (a keystroke at a time, instead of a line at a time), but the details are OS specific. 2)您可以读取“原始的,无缓冲的”I / O(一次一键击,而不是一次一行),但细节是特定于操作系统的。 Whatever you need to do on a specific OS, you almost certainly can do from Java. 无论您需要在特定操作系统上执行什么操作,您几乎可以肯定可以使用Java。

3) It sounds like you want to be able to intercept an "arrow up" key or "page down" key, as it happens, on a Windows keyboard. 3)听起来你希望能够在Windows键盘上拦截“向上箭头”键或“向下翻页”键。 Perhaps for playing a game, or for interacting with a console-mode user interface. 也许是为了玩游戏,或者是为了与控制台模式的用户界面进行交互。

4) There are several options. 4)有几种选择。 One you might wish to consider is the "robot" API, used for testing: 您可能希望考虑的是用于测试的“机器人”API:

If that's not sufficient, please give more details about exactly how you're trying to get your Java program to interact with the C program (and clarify if the platform is indeed Windows and a DOS prompt). 如果这还不够,请详细说明您如何尝试让Java程序与C程序交互(并澄清该平台是否确实是Windows和DOS提示符)。

您可以将c输出重定向到文件,然后使用java中的另一个线程拖尾文件

org.apache.commons.io.input.Tailer

The best way to do it is using Threads to read the output 最好的方法是使用Threads来读取输出

What I would do is: using a Callable (a Runnable will also work) where I give the input from the process (process.getInputStream ()) and the output where I want to store the output. 我要做的是:使用Callable(一个Runnable也可以),我从进程输入(process.getInputStream())和我想要存储输出的输出。 The same should be done for the StdErr. 对StdErr也应如此。 The resulting output can be read using whatever you like. 可以使用您喜欢的任何内容读取结果输出。

 public Object call () throws IOException {
        int bytesRead;
        byte[] b = new byte [ this.maxBlockSize ];

        try {
            while ( ( bytesRead = this.input.read ( b ) ) != -1 ) {
                this.output.write ( b, 0, bytesRead );
            }
        } finally {
            if ( this.output != null ) {
                this.output.close ();
            }
        }
        return null;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM