簡體   English   中英

使用 getchar() 從 C 程序獲取 Java 中的標准 output 時遇到問題()

[英]Trouble getting standard output in Java from a C program with getchar()

我正在嘗試從 Java 調用 C 程序並捕獲標准 output。 這是我的代碼:

try {
    ProcessBuilder pb = new ProcessBuilder("helloworld.exe");
    pb.redirectErrorStream(true);   // Merge std out and std err into same stream
    program = pb.start();           // Start program

    BufferedReader input = new BufferedReader(new InputStreamReader(program.getInputStream()));

    line = input.readLine();
    while (line != null) {
        System.out.println(line);
        line = input.readLine();
    }   
} catch (IOException e) {
    e.printStackTrace();
}

這是一個示例 c 程序:

int main(){
    printf("Hello world\n");
}

當我正在執行的程序(在本例中為 helloworld)中沒有getchar()時,這可以正常工作。 但是,如果我在 printf 之后添加一個getchar() ,我永遠不會從輸入 stream 得到任何東西。 任何想法為什么?

謝謝

As Kyle you said, you may need to flush the output stream after calling print to make sure the characters actually go to the standard output without delay. 您應該在這兩個程序中執行此操作。 這可以使用fflush(stdout); 並且可能可以在 Java 中使用System.out.flush()之類的東西來完成。

- 大衛

因為當C程序調用getchar時,C程序停止等待輸入。 而且輸入永遠不會到來,畢竟,您的 Java 程序會捕獲 stdout/stderr。 但對附加到標准輸入沒有任何作用。

使用program object 上的 Process class 中的 getOutputStream() 實例方法來獲取代表標准輸入的 stream,類似於 getInputStream()。

然后將數據發送到 C 程序所期望的 C 程序。

顯然,在將 output 發送到父進程之前,子進程(或操作系統或 JAVA 運行時或...,...)仍在等待 char ( getchar )。

如果您不需要輸入,請不要包含getchar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM