java - 为什么从 Process 的 InputStream 中读取数据是可用的

标签 java linux

Java:

Process p = Runtime.getRuntime().exec("myCommand");
final InputStream in = p.getInputStream();

new Thread()
{
    public void run()
    {
        int b;
        while ((b = in.read()) != -1) // Blocks here until process terminates, why?
            System.out.print((char) b);
    }
}.start();

CPP:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char** argv)
{
    printf("round 1\n");

    // At this point I'd expect the Java process be able
    // to read from the input stream.

    sleep(1);

    printf("round 2\n");

    sleep(1);

    printf("round 3\n");

    sleep(1);

    printf("finished!\n");

    return 0;

    // Only now InputStream.read() stops blocking and starts reading.
}

InputStream.read() 的文档指出:

This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

是的,我知道这一点(因此与 Linux 相关?):

java.lang.Process: Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.

我的问题是:

  1. 为什么 InputStream.read() 阻塞,尽管我应该在进程启动后立即获得数据?我是否遗漏了任何一方的东西?

  2. 如果是 linux 相关的,有什么方法可以不阻塞地读取进程的输出流吗?

最佳答案

Why does reading from Process' InputStream block although data is available

事实并非如此。这里的问题是当您认为数据可用时,数据并不可用,这是由发送方的缓冲造成的。

您可以根据@MarkkuK. 的评论使用 fflush() 来克服这个问题,或者告诉 stdio 不要缓冲 stdout所有,按照你的。

关于java - 为什么从 Process 的 InputStream 中读取数据是可用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18479152/

相关文章:

c# - 在 linux 服务上处理 kill - .NET Core 1.1

linux - 允许用户仅选择一组显示的 ID

java - 如何创建具有构建路径使用的依赖项的 Maven 项目 jar?

java - Java:使用Java Media Framework的音频捕获设备列表

Java 不包括 100 个储物柜中的 100 个

c++ - 在 C/C++ 中检测密码保护的 MS Office 文件

linux - FASM:字符串存储和控制台输出

java - JPanel#setVisible 不工作。

java - Map 的 equals() 用于作为数组的键

c - 使用 C 语言的 linux 系统命令