ProcessBuilder and ProcessHandle
ProcessBuilder starts an operating system program from Java and connects to its input, output and exit code. Done carelessly it deadlocks, hangs or opens a command injection hole. This page explains how a child process is connected to the JVM, runs real commands with the safe patterns for output, input and timeouts, reproduces the full-pipe deadlock and a command injection, uses redirects and pipelines, inspects processes with ProcessHandle, and measures what starting a process costs.
Contents
How Java runs another program Running commands: output, environment, input and timeouts The full-pipe deadlock Command injection: why arguments beat a shell Redirects and the Java 17 reader and writer ProcessHandle: inspecting and watching processes What starting a process costs Choosing how to run a process
How Java runs another program
Starting a process asks the operating system to run a program as a child of the JVM. On Linux and macOS the JDK does this with posix_spawnforkexecCreateProcess
- the child's standard input is
: what Java writes, the child reads;process.getOutputStream() - the child's standard output is
;process.getInputStream() - the child's standard error is
.process.getErrorStream()
A pipe has a small fixed buffer, 64 KB by default on Linux. When it is full, the writer blocks until someone reads. A child whose output nobody reads therefore stops, which is the cause of most "my process hangs" problems. The other big risk is the command line: ProcessBuilder$
| API | Since | Best for |
|---|---|---|
Runtime.exec(String) | Java 1.0; deprecated in Java 18 | Nothing in new code: it splits the string at spaces |
ProcessBuilder | Java 5 | Starting programs with arguments, directory, environment and redirects |
Redirect.DISCARDProcessBuilder.startPipeline | Java 9 | Ignoring output; chaining programs without a shell |
ProcessHandle | Java 9 (JEP 102) | Inspecting, waiting for and stopping any process, including the JVM itself |
Process.inputReaderoutputWritererrorReader | Java 17 | Text I/O with the child without wrapping streams by hand |
The examples ran on JDK 21 on Linux and call standard Unix commands (lssortsh
Running commands: output, environment, input and timeouts
Five common tasks in one program: read a command's output, set a working directory and environment variable, write to a child's input, give up after a timeout, and chain three programs.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class RunCommands {
public static void main(String[] args) throws IOException, InterruptedException {
// 1. Run a command and read its output; arguments are separate list items, not one string
Process ls = new ProcessBuilder("ls", "-1", "/usr/bin").start();
long count;
try (BufferedReader out = new BufferedReader(
new InputStreamReader(ls.getInputStream(), StandardCharsets.UTF_8))) {
count = out.lines().count();
}
System.out.println("ls exit code " + ls.waitFor() + ", over 100 entries: " + (count > 100));
// 2. Merge stderr into stdout, set the working directory and an environment variable
Path dir = Files.createTempDirectory("proc");
String script = "echo \"dir=$(pwd) GREETING=$GREETING\"; ls missing-file";
ProcessBuilder pb = new ProcessBuilder("sh", "-c", script)
.directory(dir.toFile())
.redirectErrorStream(true);
pb.environment().put("GREETING", "hello");
Process sh = pb.start();
String text = new String(sh.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
System.out.print(text.replace(dir.toString(), "<tempdir>"));
System.out.println("sh exit code: " + sh.waitFor() + " (non-zero: ls failed)");
// 3. Write to the process's stdin
Process sort = new ProcessBuilder("sort").start();
try (OutputStream in = sort.getOutputStream()) {
in.write("pear\napple\nfig\n".getBytes(StandardCharsets.UTF_8));
} // closing stdin = end of input
String sorted = new String(sort.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
System.out.println("sorted: " + sorted.lines().toList());
sort.waitFor();
// 4. A timeout, then forcible termination
Process sleeper = new ProcessBuilder("sleep", "10").start();
boolean finished = sleeper.waitFor(200, TimeUnit.MILLISECONDS);
System.out.println("sleep finished in 200 ms: " + finished);
sleeper.destroyForcibly().waitFor();
System.out.println("after destroyForcibly, alive: " + sleeper.isAlive());
// 5. Pipelines (Java 9): ls | grep java | wc -l, without a shell
List<Process> pipeline = ProcessBuilder.startPipeline(List.of(
new ProcessBuilder("ls", "/usr/bin"),
new ProcessBuilder("grep", "^java"),
new ProcessBuilder("wc", "-l")));
Process last = pipeline.get(pipeline.size() - 1);
String n = new String(last.getInputStream().readAllBytes(), StandardCharsets.UTF_8).strip();
System.out.println("pipeline found java commands: " + (Integer.parseInt(n) >= 1));
Files.delete(dir);
}
}
Output:
ls exit code 0, over 100 entries: true
dir=<tempdir> GREETING=hello
ls: cannot access 'missing-file': No such file or directory
sh exit code: 2 (non-zero: ls failed)
sorted: [apple, fig, pear]
sleep finished in 200 ms: false
after destroyForcibly, alive: false
pipeline found java commands: true
is three list items, not one string. The program read all lines and only then calledls -1 /usr/bin , which returned exit code 0.waitFor()- The shell script ran in a temporary directory with
added to the inherited environment.GREETING=hello merged the error message of the failingredirectErrorStream(true) into the same stream, and the non-zero exit code 2 signalled the failure. Always check the exit code; a failed command often prints nothing to stdout.ls read from its standard input until end of file. Closing the output stream sent that end of file; without the close,sort would have waited forever.sort returned false for a 10-secondwaitFor(200, MILLISECONDS) , andsleep killed it.destroyForcibly() asks politely (SIGTERM on Unix),destroy() does not (SIGKILL).destroyForcibly() connectedstartPipeline ,ls andgrep directly, each one's output to the next one's input, without a shell.wc
The full-pipe deadlock
A child that writes a lot to standard error while the parent waits for it, or reads only standard output, will block once the stderr pipe is full. The child here prints one result line and 200 KB of warnings, more than the 64 KB pipe can hold.
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class PipeDeadlock {
// A child that writes 1 line to stdout and 200 KB of warnings to stderr
static final String NOISY = "echo result; head -c 200000 /dev/zero | tr '\\0' 'w' >&2";
public static void main(String[] args) throws Exception {
// 1. Wrong: wait for the process before reading stderr; the stderr pipe fills up
Process p = new ProcessBuilder("sh", "-c", NOISY).start();
boolean done = p.waitFor(2, TimeUnit.SECONDS);
System.out.println("1. waitFor without reading stderr finished: " + done
+ " (child is stuck writing to a full pipe)");
p.destroyForcibly().waitFor();
// 2. Fix A: merge stderr into stdout and read everything
Process merged = new ProcessBuilder("sh", "-c", NOISY).redirectErrorStream(true).start();
int bytes = merged.getInputStream().readAllBytes().length;
System.out.println("2. merged streams: read " + bytes + " bytes, exit "
+ merged.waitFor());
// 3. Fix B: read stderr on another thread while reading stdout here
Process both = new ProcessBuilder("sh", "-c", NOISY).start();
CompletableFuture<Integer> err = CompletableFuture.supplyAsync(() -> {
try {
return both.getErrorStream().readAllBytes().length;
} catch (IOException e) {
throw new IllegalStateException(e);
}
});
String out = new String(both.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
System.out.println("3. stdout " + out.strip() + ", stderr " + err.get() + " bytes, exit "
+ both.waitFor());
// 4. Fix C: throw stderr away if you do not need it (Java 9)
Process quiet = new ProcessBuilder("sh", "-c", NOISY)
.redirectError(Redirect.DISCARD).start();
System.out.println("4. DISCARD: stdout " + new String(quiet.getInputStream()
.readAllBytes(), StandardCharsets.UTF_8).strip() + ", exit " + quiet.waitFor());
}
}
Output:
1. waitFor without reading stderr finished: false (child is stuck writing to a full pipe)
2. merged streams: read 200007 bytes, exit 0
3. stdout result, stderr 200000 bytes, exit 0
4. DISCARD: stdout result, exit 0
- Waiting before reading did not finish within 2 seconds: the child was blocked writing warnings into a full pipe, and the parent was blocked waiting for the child. With an untimed
, both would wait forever.waitFor() merged both streams into one, which the parent read to the end: 200,007 bytes, the 7-byte result line plus the warnings.redirectErrorStream(true)- Reading stderr on another thread while reading stdout on this one keeps both pipes drained and the two streams separate.
sends stderr to the null device, so it can never fill up. Redirecting to a file withRedirect.DISCARD works the same way and keeps the text.Redirect.to
The rule: every stream of a child must be read, redirected or discarded, and waitFor()
Command injection: why arguments beat a shell
A user supplies a file name that contains shell syntax. The program passes it once through sh -cProcessBuilder$
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Injection {
static String run(ProcessBuilder pb) throws IOException, InterruptedException {
Process p = pb.redirectErrorStream(true).start();
String out = new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
p.waitFor();
return out.strip().replace("\n", " | ");
}
public static void main(String[] args) throws Exception {
// A file name typed by a user: harmless-looking, but it contains shell syntax
String userInput = "report.txt; echo INJECTED COMMAND RAN";
// Unsafe: building a shell command line from the input
System.out.println("via sh -c: " + run(new ProcessBuilder("sh", "-c",
"echo looking for " + userInput)));
// Safe: each argument is passed as-is to the program; no shell parses it
System.out.println("as arguments: " + run(new ProcessBuilder("echo", "looking for",
userInput)));
// Arguments with spaces stay one argument; quotes are not needed and not removed
System.out.println("printf args: " + run(new ProcessBuilder("printf", "[%s]\\n",
"two words", "'quoted'", "$HOME")));
}
}
Output:
via sh -c: looking for report.txt | INJECTED COMMAND RAN
as arguments: looking for report.txt; echo INJECTED COMMAND RAN
printf args: [two words] | ['quoted'] | [$HOME]
- Through
, the semicolon ended the first command and the shell ran the attacker's second one: "INJECTED COMMAND RAN". With a real command instead ofsh -c , that is remote code execution.echo - As a separate argument, the same text reached
unchanged, semicolon and all. No shell parsed it, so nothing was executed.echo - Each list element is exactly one argument: "two words" stayed together, the single quotes were passed literally, and
was not expanded. Quoting rules only exist when a shell is involved.$HOME - If a shell is unavoidable, pass user data as positional parameters,
, never by concatenating it into the script. On Windows, programs parse their own command line, so arguments with quotes and spaces need extra care even without a shell.sh -c 'grep -- "$1" file' sh "$input"
Redirects and the Java 17 reader and writer
A child's streams do not have to pass through the JVM at all. The program appends output to a file, feeds input from a file, uses the Java 17 text helpers, and finally lets a child print directly to the JVM's own console.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.lang.ProcessBuilder.Redirect;
import java.nio.file.Files;
import java.nio.file.Path;
public class Redirects {
public static void main(String[] args) throws Exception {
Path dir = Files.createTempDirectory("redir");
File log = dir.resolve("out.log").toFile();
// 1. Output straight to a file, appending; the JVM never sees the bytes
for (int i = 1; i <= 2; i++) {
new ProcessBuilder("echo", "run " + i).redirectOutput(Redirect.appendTo(log))
.start().waitFor();
}
System.out.println("1. file now contains: " + Files.readAllLines(log.toPath()));
// 2. Input from a file
Path input = dir.resolve("in.txt");
Files.writeString(input, "b\nc\na\n");
Process sort = new ProcessBuilder("sort").redirectInput(input.toFile()).start();
try (BufferedReader r = sort.inputReader()) { // Java 17
System.out.println("2. sorted from file: " + r.lines().toList());
}
sort.waitFor();
// 3. Writing with outputWriter (Java 17), reading with inputReader
Process tr = new ProcessBuilder("tr", "a-z", "A-Z").start();
try (BufferedWriter w = tr.outputWriter()) {
w.write("hello process");
}
try (BufferedReader r = tr.inputReader()) {
System.out.println("3. tr says: " + r.readLine());
}
System.out.println(" exit " + tr.waitFor());
// 4. INHERIT: the child writes directly to this JVM's console
System.out.flush();
int rc = new ProcessBuilder("echo", "4. printed by the child itself")
.inheritIO().start().waitFor();
System.out.println(" inherited IO, exit " + rc);
Files.delete(log.toPath());
Files.delete(input);
Files.delete(dir);
}
}
Output:
1. file now contains: [run 1, run 2]
2. sorted from file: [a, b, c]
3. tr says: HELLO PROCESS
exit 0
4. printed by the child itself
inherited IO, exit 0
made two runs write to the same log; the bytes went from the child straight to the file.Redirect.appendTo(file) truncates instead.Redirect.to(file) connected the file toredirectInput(file) 's standard input.sort (Java 17) wraps the output stream in ainputReader() using the native charset; pass a charset to it when the child's encoding differs.BufferedReader gives aoutputWriter() on the child's input. Closing it sent end of file, soBufferedWriter finished and printed "HELLO PROCESS".tr gave the child the JVM's own standard streams, so its line appeared in the program's output without any reading code. That suits running a build tool or an interactive program.inheritIO()
ProcessHandle: inspecting and watching processes
ProcessHandlesleep
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Handles {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessHandle me = ProcessHandle.current();
System.out.println("this JVM's pid is a positive number: " + (me.pid() > 0));
boolean isJava = me.info().command().map(c -> c.endsWith("java")).orElse(false);
System.out.println("our command ends with 'java': " + isJava);
Process child = new ProcessBuilder("sleep", "5").start();
ProcessHandle h = child.toHandle();
System.out.println("child parent is this JVM: "
+ h.parent().map(p -> p.pid() == me.pid()).orElse(false));
System.out.println("children of this JVM: " + me.children().count());
// onExit: get notified asynchronously when the process ends
h.onExit().thenAccept(p -> System.out.println("onExit callback: child ended"));
h.destroy();
child.waitFor(2, TimeUnit.SECONDS);
Thread.sleep(100);
System.out.println("child alive: " + h.isAlive() + ", exit value: " + child.exitValue());
}
}
Output:
this JVM's pid is a positive number: true
our command ends with 'java': true
child parent is this JVM: true
children of this JVM: 1
onExit callback: child ended
child alive: false, exit value: 143
is the JVM itself;ProcessHandle.current() gives the command, arguments, start time and user when the operating system allows reading them, which is why each value is aninfo() .Optional- The child's parent was this JVM, and
found it.children() also includes grandchildren, which matters becausedescendants() on a shell does not stop the programs the shell started.destroy() returns aonExit() completed when the process ends, so the program can react without a thread blocked inCompletableFuture .waitFor()- The exit value 143 is 128 + 15: on Unix a process killed by signal 15 (SIGTERM, sent by
) reports 128 plus the signal number.destroy()
What starting a process costs
Starting a process is far more expensive than calling a method. The program starts three programs repeatedly and reports the average time from start()waitFor()
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
public class StartCost {
static long averageMicros(ProcessBuilder pb, int runs) throws Exception {
long best = Long.MAX_VALUE;
for (int round = 0; round < 3; round++) {
long t0 = System.nanoTime();
for (int i = 0; i < runs; i++) {
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);
}
best = Math.min(best, System.nanoTime() - t0);
}
return best / runs / 1000;
}
public static void main(String[] args) throws Exception {
String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
System.out.println("average time to start a process and wait for it, best of 3:");
System.out.printf(" /bin/true %,7d us%n",
averageMicros(new ProcessBuilder("true"), 50));
System.out.printf(" sh -c true %,7d us%n",
averageMicros(new ProcessBuilder("sh", "-c", "true"), 50));
System.out.printf(" java -version %,7d us%n",
averageMicros(new ProcessBuilder(java, "-version")
.redirectErrorStream(true)
.redirectOutput(ProcessBuilder.Redirect.DISCARD), 5));
}
}
Output (2-CPU Linux machine, JDK 21, best of 3 rounds):
average time to start a process and wait for it, best of 3:
/bin/true 1,841 us
sh -c true 1,758 us
java -version 31,840 us
- Even
, a program that does nothing, took on the order of a millisecond or two to start and finish, and starting it throughtrue cost about the same here. Calling a program per item in a loop over thousands of items costs seconds.sh -c - Starting another JVM took tens of milliseconds, even for
. For work that Java can do itself, such as compressing files or calling HTTP services, use the Java API instead of a child process; for the JDK's own tools,-version runsjava.util.spi.ToolProvider ,javac and others inside the current JVM.jar
Choosing how to run a process
| Situation | Use |
|---|---|
| Run a program with arguments | new ProcessBuilder("prog", arg1, arg2) |
| Read output and errors together | redirectErrorStream(true)waitFor() |
| Ignore output safely | Redirect.DISCARD |
| Keep output in a log file | Redirect.toRedirect.appendTo |
| Avoid hanging forever | waitFor(timeout, unit)destroy()destroyForcibly() |
| Chain programs | ProcessBuilder.startPipeline |
| React when a process ends | process.onExit()ProcessHandle.onExit() |
| Run JDK tools | ToolProvider |
See