[英]Why does reading from Process' InputStream block altough data is available
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()的文檔說明:
此方法將阻塞,直到輸入數據可用,檢測到流的末尾或拋出異常。
是的,我知道這個(因此linux相關?):
java.lang.Process:由於某些本機平台僅為標准輸入和輸出流提供有限的緩沖區大小,因此無法及時寫入輸入流或讀取子進程的輸出流可能導致子進程阻塞甚至死鎖。
我的問題是:
為什么InputStream.read()阻塞雖然我應該在進程啟動后就已經有了數據? 我錯過了兩邊的東西嗎?
如果它與linux相關,有沒有辦法從流程的輸出流中讀取而不會阻塞?
盡管數據可用,為什么要從Process'InputStream塊讀取
它沒有。 這里的問題是,當您認為數據不可用時,數據不可用,並且這是由發送方緩沖引起的。
您可以使用fflush()
根據@MarkkuK。的評論,或者告訴stdio
不要緩沖stdout
,就像你的那樣。
我在這里發布了另一個解決方案,它包括在從Process
流中讀取任何內容之前使用InputStream#available()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.