Search code examples
javaprocessbuilderinteractive-shell

(Blocking) interactive shell via ProcessBuilder


I built an interactive EXE which means that you can continuously send new commands to it and it will process them.

An automation of this can be implemented in Java according to this answer. However, when sending the command, the code will not wait till the command has finished. Instead, it will return the control back to the caller right away which might lead to race conditions: If the sent command was supposed to write a file, maybe the file isn't created yet before it is accessed. How can a command be sent, the output read and as soon as some input command is expected again, the sendCommand() call returns?

public synchronized void sendCommand(String command) throws IOException
{
    byte[] commandBytes = (command + "\n").getBytes(UTF_8.name());
    outputStream.write(commandBytes);
    outputStream.flush();
}

Preferably also returning the process output in the meantime. This would be the default behavior of a non-interactive shell command which terminates once finished executing. read() blocks indefinitely until the process terminates and I do not want to hardcode the length of the expected process output or similar hacks to circumvent this shortcoming.


Solution

  • I decided to rewrite my binary to be non-interactive again. It turns out the expected performance gain was negligible so there was no more reason to keep it interactive and go through an increased implementation hassle.