简体   繁体   English

从C程序读取输出时BufferedReader挂起

[英]BufferedReader hangs when reading output from a C program

I'm writing a program in Java that sends commands to a C program and reads its output, but I see that it hangs when I try to actually read the output. 我正在用Java编写一个程序,该程序将命令发送到C程序并读取其输出,但是当我尝试实际读取输出时,我发现它挂起了。 The code is: 代码是:

    import java.io.*;
    public class EsecutoreC {
        private String prg;
        OutputStream stdin=null;
        InputStream stderr=null;
        InputStream stdout=null;
        BufferedReader br;
        Process pr;
        public EsecutoreC(String p){
            prg=p;
            try {
                pr=Runtime.getRuntime().exec(prg);
                stdin=pr.getOutputStream();
            stderr=pr.getErrorStream();
            stdout=pr.getInputStream();
                    br=new BufferedReader(new InputStreamReader(stdout));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public void sendInput(String line){
        line=line+"\n";
        try {
            stdin.write(line.getBytes());
            stdin.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }

}
public BufferedReader getOutput(){
    return br;
}
}

When I need to read the program's output, I just use getOutput to get the BufferedReader and then I call readLine(). 当我需要读取程序的输出时,只需使用getOutput获取BufferedReader,然后调用readLine()。 I see that the program hangs since I put a println right after the call to readLine and nothing gets printed. 我看到程序挂起,因为我在对readLine的调用之后立即放置了一个println,但未打印任何内容。 I also add a \\n after each line of output in the C program. 我还在C程序的每一行输出之后添加\\ n。 Also, is there a way to show the window of the program called through Runtime.getRuntime().exec()? 另外,有没有一种方法可以显示通过Runtime.getRuntime()。exec()调用的程序窗口? so that I could check if there is any other problem when I send a string to it or when I read from its output. 这样,当我向它发送字符串或从其输出读取时,我可以检查是否还有其他问题。

When you call readLine() the BufferedReader will block until there is a new line character '\\n' in the output. 当您调用readLine() ,BufferedReader将阻塞,直到输出中出现换行符'\\n'为止。 Try calling the C program from a terminal / command line see if the output really terminates in a new line. 尝试从终端/命令行调用C程序,看看输出是否真的以新行终止。

Alternatively you could just read(1) one char at a time (no need for a BufferedReader then) and print it immediately. 或者,您可以一次只read(1)一个字符(然后不需要BufferedReader )并立即打印它。

Encoding does not affect the '\\n' character. 编码不会影响'\\n'字符。

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

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