2

I am trying to interact with another process in Java. It goes like this...

Runtime rt;
Process pr=rt.exec("cmd");

then I send some commands to the process using...

BufferedReader processOutput = new BufferedReader(new InputStreamReader(pr.getInputStream()));
BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(pr.getOutputStream()));

processInput.write("gdb");
processInput.flush();

I don't care about the output for now.. so I try to ignore it using..

while(processOutput.readLine() != null);

but this loops hangs forever. I know this is because process is still running and doesn't sends a null. I don't want to terminate it now. I have to send commands based on user Input and then get the output..

How to do this? In other words I want to flush the Process output stream or ignore it after executing some commands and read it only when I want to.

1 Answer 1

2

Use a separate thread to read the output. This way, as long as there is output it will be read, but will not block you.

For example, create such a class:

public class ReaderThread extends Thread {

    private BufferedReader reader = null;
    public ReaderThread(BufferedReader reader) {
        this.reader = reader;
    }

    @Override
    public void run() {
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
        catch(IOException exception) {
            System.out.println("!!Error: " + exception.getMessage());
        }
    }
}

And in your main class, instead of while(processOutput.readLine() != null);, call:

ReaderThread reader = new ReaderThread(processOutput);
reader.start();
Sign up to request clarification or add additional context in comments.

5 Comments

@MByD- I dint quite get it... Lets say I run the process in another thread and then in main thread I try.. while(processOutput.readLine() != null); It will still block...
I wasn't clear...run the reading in separate thread. I will add an example in a minute or two.
@MByd- If I'm correct the thread will keep on running and outputting till the process ends. This won't block but how can I selectively process the output? Say when I send a command "x/64 $ESP".. I want to do something with the output.
Add some synchronized flags in this thread, and process the output accordingly. This depends on your needs, but it is possible. As you saw in my example, you can process the output in the way you want.
@MByD- How to add "synchronized flags"? The output of "cmd" is not under control. How to check if the end of the output of command "x/64 $ESP" is reached?