BufferedReader hangs when reading output from a C program

元气小坏坏 提交于 2019-12-11 20:04:49

问题


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. 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(). I see that the program hangs since I put a println right after the call to readLine and nothing gets printed. I also add a \n after each line of output in the C program. Also, is there a way to show the window of the program called through 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.


回答1:


When you call readLine() the BufferedReader will block until there is a new line character '\n' in the output. Try calling the C program from a terminal / command line see if the output really terminates in a new line.

Alternatively you could just read(1) one char at a time (no need for a BufferedReader then) and print it immediately.

Encoding does not affect the '\n' character.



来源:https://stackoverflow.com/questions/11266861/bufferedreader-hangs-when-reading-output-from-a-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!