1. Introduction
An interactive process is a program that doesn’t just do something by itself, but waits for you to “talk” to it. It accepts input from the user and responds.
Classic examples are interpreters like Python, bash, or PowerShell. They patiently wait for commands, execute them, and show the result. There are others too: interactive utilities like a calculator, console databases (psql, sqlite3), or even text editors like vi and nano. Sometimes even an ordinary script can become interactive if it asks you for parameters or answers during execution.
Starting such processes from Java is not a walk in the park. It’s not enough to just “send a command and get the result.” You need to set up a real dialogue: send data on time and read replies, like in a live conversation.
Imagine messaging a friend. You send a message, wait for a reply, then write again. That’s roughly how Java interacts with an external process when you set up stream handling correctly.
Setting up two-way communication
Every process has three “channels”: input (stdin), output (stdout), and error (stderr). Through the first you can send data to the process, through the second you get results, and the third is used for error messages.
The key is to avoid letting the process “freeze” while waiting. If you read only the regular output and ignore the error stream, the process can hang as if it’s waiting for you to pay attention to its complaints. The same goes the other way: if you send something to input but don’t read the replies, the process may stall, not knowing where to put the accumulated data.
Therefore, when working with interactive processes, it’s important to maintain a two-way exchange—like in a normal conversation where both sides listen and respond, rather than talking into the void.
Interactive communication diagram
+---------------------+
| Java program |
+---------------------+
| ^
v |
stdin stdout/stderr
| ^
+---------------------+
| External process |
+---------------------+
- Java writes to the process’s input stream (stdin of the process).
- Java reads from the process’s stdout and stderr.
- All of this can happen at the same time!
2. Practice: interactive communication with an external process
Let’s consider a practical example: we will launch an external process (for example, the Python interpreter or a simple echo script), send it lines, and read the responses.
Example 1: Running a Python script that waits for input
First, create a simple Python script (call it echo_bot.py):
# echo_bot.py
while True:
try:
line = input()
if line == "exit":
print("Bye!")
break
print("Echo:", line)
except EOFError:
break
This script waits for input and replies to each line with "Echo: ...". If you enter "exit", it exits.
How do we start and “talk” to this script from Java?
1. Start the process
ProcessBuilder builder = new ProcessBuilder("python", "echo_bot.py");
Process process = builder.start();
2. Prepare streams for communication
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
3. Implement the dialogue
// Send a line to the process
writer.write("Hello, process!\n");
writer.flush();
// Read the response
String response = reader.readLine();
System.out.println("Process response: " + response);
4. Repeat until you’re done
Let’s wrap this into a simple loop so the user can type in the console, Java sends it to the process, and prints the reply.
Full example: a Java chat with an external process
import java.io.*;
public class InteractiveProcessDemo {
public static void main(String[] args) throws IOException {
ProcessBuilder builder = new ProcessBuilder("python", "echo_bot.py");
Process process = builder.start();
// Streams for communicating with the process
BufferedWriter toProcess = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader fromProcess = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter lines to send to the process (type exit to quit):");
while (true) {
// Read a line from the user
String line = userInput.readLine();
if (line == null) break;
// Send it to the process
toProcess.write(line + "\n");
toProcess.flush();
// Read the process response
String response = fromProcess.readLine();
System.out.println("Process response: " + response);
if ("exit".equals(line)) break;
}
// Terminate the process
process.destroy();
}
}
Code comments:
- We use three streams: to read from the user (System.in), to write to the process (process.getOutputStream()), and to read the response (process.getInputStream()).
- After each line is sent to the process, we immediately read the response via readLine().
- If the user enters "exit", the program breaks the loop and destroys the process (process.destroy()).
3. Why are simultaneous reading and writing important?
In real tasks, a process may output a lot of data and sometimes ask for input several times in a row. If you don’t read the process output in time, its internal buffer can fill up, and the process will “hang,” waiting for someone to read its messages. Similarly, if you don’t send data to input, the process may wait and “freeze” as well.
Deadlock: when everything is stuck
Deadlock is a situation where two participants (or a thread and a process) are waiting for each other, and neither can proceed.
Example of a deadlock:
- Java is waiting for the process to write something to stdout.
- The process is waiting for Java to write something to its stdin.
- Both are waiting—nobody is working.
Solution: separate threads for reading and writing
To avoid deadlock, it’s common to use separate threads (Thread) to read the process’s stdout and stderr simultaneously. For example, you can create two threads: one reads stdout, the other reads stderr, while the main thread writes to stdin.
Minimal example with a separate thread for stderr
// Read stderr in a separate thread
Thread errorThread = new Thread(() -> {
try (BufferedReader errorReader = new BufferedReader(
new InputStreamReader(process.getErrorStream()))) {
String line;
while ((line = errorReader.readLine()) != null) {
System.err.println("stderr: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
});
errorThread.start();
4. Practice: interactive communication with a calculator
We don’t always have Python. Let’s try to run a standard command that is available almost everywhere—for example, a command-line calculator. On Linux/Mac this can be bc (basic calculator), on Windows—cmd or powershell.
Example: interactive communication with bc (Linux/Mac)
ProcessBuilder builder = new ProcessBuilder("bc");
Process process = builder.start();
BufferedWriter toProcess = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader fromProcess = new BufferedReader(new InputStreamReader(process.getInputStream()));
toProcess.write("2 + 2\n");
toProcess.flush();
String result = fromProcess.readLine();
System.out.println("Calculator response: " + result);
toProcess.write("quit\n");
toProcess.flush();
process.destroy();
On Windows: you can try launching cmd and passing commands to it, but it will be more complicated (different syntax is needed). Usually, for demonstrating interactivity, you use utilities available on both platforms or write your own mini-scripts.
5. Problems and pitfalls
Stream buffering
Sometimes a process doesn’t output data immediately but accumulates it in an internal buffer and “releases” it only when the buffer is full or when it receives a newline character ("\n"). This can lead to a situation where you don’t see a response for a long time, although the process has already “prepared” it.
Tip:
- Always terminate lines with "\n" when writing to the process’s stdin.
- If you write your own scripts, use flush() after every output.
Deadlock due to incorrect stream handling
If you don’t read stderr and the process writes a lot there, it can hang waiting for someone to read the errors.
Tip:
Always read both the process’s stdout and stderr, preferably in separate threads.
The process has exited—and you’re still writing
If the process has already finished and you continue writing to its input, you’ll get an IOException: "Stream closed".
7. Best practices: interactive communication
Using ExecutorService for concurrent reading
Instead of hand-rolling threads for reading output and errors, it’s convenient to use an ExecutorService (for example, a pool of two threads):
import java.util.concurrent.*;
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> {
try (BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = out.readLine()) != null) {
System.out.println("stdout: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
});
executor.submit(() -> {
try (BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
String line;
while ((line = err.readLine()) != null) {
System.err.println("stderr: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
});
Properly closing streams
After you finish with the process, be sure to close all streams (stdin, stdout, stderr) so you don’t leak resources.
toProcess.close();
fromProcess.close();
process.destroy();
executor.shutdown();
8. Final example: interactive communication with an external process
Let’s put it all together. The example below works like an interactive “chat” between the user and an external process (for example, a Python script or a calculator).
import java.io.*;
import java.util.concurrent.*;
public class InteractiveProcessUniversal {
public static void main(String[] args) throws IOException {
// Replace with your command — e.g., "python echo_bot.py" or "bc"
ProcessBuilder builder = new ProcessBuilder("python", "echo_bot.py");
Process process = builder.start();
ExecutorService executor = Executors.newFixedThreadPool(2);
// Reading the process stdout
executor.submit(() -> {
try (BufferedReader out = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = out.readLine()) != null) {
System.out.println("[process] " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
});
// Reading the process stderr
executor.submit(() -> {
try (BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
String line;
while ((line = err.readLine()) != null) {
System.err.println("[process-err] " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
});
// Main thread: writes to the process stdin
try (BufferedWriter toProcess = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in))) {
System.out.println("Enter lines for the process (type exit to quit):");
String line;
while ((line = userInput.readLine()) != null) {
toProcess.write(line + "\n");
toProcess.flush();
if ("exit".equals(line)) break;
}
}
process.destroy();
executor.shutdown();
}
}
9. Common mistakes when working interactively with processes
Error #1: Not reading the process’s stderr. If the process writes many errors but stderr isn’t being read, it can hang. Even if you’re sure there will be no errors—read stderr!
Error #2: Not closing streams. If you don’t close the process streams, you may leak resources and sometimes block the process from terminating.
Error #3: Platform differences in commands. Commands and their syntax differ between Windows and Unix-like systems. Detect the OS and choose the appropriate command.
Error #4: The program “hangs”—output isn’t being flushed. If you forget to call flush() after writing to a stream, data may “stick” in a buffer and never reach the process.
Error #5: Output buffering in the external process. Sometimes a process doesn’t output data until enough characters have accumulated or it receives "\n". If you write your own scripts—use flush().
Error #6: Deadlock due to simultaneously waiting for input/output. If the main thread is waiting for the process’s output while the process is waiting for input, both can “hang.” Use separate threads for reading/writing.
Error #7: “Stream closed” exception when writing to a finished process. Check whether the process is alive before writing to its stdin. If you make a mistake, you will get an IOException: "Stream closed".
GO TO FULL VERSION