Search code examples
javalinuxbufferedreader

How to read lines from a C script from Java's BufferedReader?


I'm running this java program on a raspberry pi. The program is supposed to run the script "hello_pixy" and scan what it prints out. When I run hello_pixy manually, it prints out lines normally (Via C's printf line). But when I run the program, nothing is printed out and the BufferedReader didn't read any lines.

If I substitute the script for something like "ls", then the BufferedReader reads it and prints it out. Is there a way I can change the "printf"s in C to send to the InputStream (I don't really know C, just enough from Java experience)?

    Process process = null;

    try {
        process = Runtime.getRuntime().exec("sudo .ss/pixy/build/hello_pixy/hello_pixy");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } //for Windows

    try {
        process.waitFor();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;

    String print = "";
    try {
        while ((line = reader.readLine()) != null) {
            print += line;
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    System.out.println("\nCodescan:\n\n" + print);

The code I'm executing is here: https://github.com/De-etz/pixy/blob/master/src/host/hello_pixy/hello_pixy.cpp


Solution

  • You're doing this back to front. You must read all the process's output first, and then call waitFor(). Your way you will probably just deadlock, as the process can't exit until it has produced all its output, and if you're not reading it, it will eventually block.

    Notes:

    1. C is not a scripting language, and a compiled program is not a script by definition.
    2. Code that depends on the success of code in a prior try block must be inside that try block. At present you are continuing after exceptions as though they didn't happen. Don't write code like this.