Running Shell Commands from Java Safely: ProcessBuilder, Process API and Timeouts
Why Java code that shells out hangs, leaks processes or runs the wrong command, reproduced with runnable demos: the pipe-buffer deadlock, timeouts that do not kill, orphaned grandchildren, PATH and environment traps, ProcessHandle, and shell and option injection, plus a safe runner helper.
A Java service shells out to git, ffmpeg, a PDF converter, or a command an AI agent just asked it to run. It works on your laptop. In production it hangs, or leaves processes behind, or runs something it was never meant to run. All three failures come from the same small API, and none of them throws an exception.
This post starts from what a child process is, reproduces each failure with a program you can run, and ends with a ~135-line helper that avoids all of them. Every output block below is copied from a file in the companion repository, produced by a real run.
Tested against: Temurin JDK 25.0.5.1+2 (LTS) on Linux 6.18, --release 25, JUnit Jupiter 5.11.0, 14 passing contract tests. Process.waitFor(Duration) is @since 24 in the JDK source; on JDK 21 only the waitFor(long, TimeUnit) form exists. The demos call sh, sleep, head, tr, cat, wc, ls, sort and uniq, so they are Linux/macOS programs; I did not run them on Windows.
A child process is another program, connected to yours by three pipes
When Java starts a command it does not run it “inside” the JVM. The operating system creates a separate process with its own memory, its own PID and its own exit code, and wires its standard input, standard output and standard error to your JVM through pipes. ProcessBuilder is where you describe the command; start() launches it; the Process you get back is your handle on the pipes and the lifetime.
The picture is the whole mental model, and the rest of the post is consequences of it. Two of the arrows carry data towards you, so you have to read them. All three are finite buffers, so somebody has to keep up. And the child can start children of its own, which the pipes know nothing about.
The smallest thing that works, from BasicsDemo.java:
Process p = new ProcessBuilder("echo", "hello from a child process").start();
String line = new String(p.getInputStream().readAllBytes()).strip();
int exit = p.waitFor();
System.out.println("stdout = " + line);
System.out.println("exit code = " + exit);
== 1. the smallest thing that works
stdout = hello from a child process
exit code = 0
Failure comes in two shapes, and they are handled in different places. A command that runs and fails is not an exception; you get a non-zero exit code and whatever it wrote to stderr. A command that cannot be started at all is an IOException thrown by start():
== 2. a failing command is NOT an exception: it is a non-zero exit code
stderr = ls: cannot access '/definitely/not/here': No such file or directory
exit code = 2
== 3. a command that does not exist IS an exception, thrown by start()
IOException: Cannot run program "no-such-binary-xyz": Exec failed, error: 2 (No such file or directory)
There is no shell here.new ProcessBuilder("echo", "*.txt", "$HOME", "a|b") prints those four strings literally, because nothing expands globs, variables or pipes. This is the safe default and also the first surprise for anyone porting a one-liner from a terminal. The same output file shows it: stdout = *.txt $HOME a|b. If you need a pipe, either use ProcessBuilder.startPipeline (below) or consciously invoke sh -c, and then read the injection section first.
Going further: exitValue() too early, and what destroyForcibly() returnsexitValue() on a process that is still running throws IllegalThreadStateException, so it is a way to read a result, never a way to check whether the process has finished; use waitFor or isAlive() for that. After destroyForcibly() the exit code on Linux is 137, which is 128 plus signal 9 (SIGKILL). A plain destroy() sends SIGTERM and gives 143. Output from output/01-basics.txt:
== 4. exitValue() before the process ends throws
IllegalThreadStateException: process hasn't exited
waitFor(200ms) returned false (false = still running, true = exited)
after destroyForcibly(): exit code = 137 (128 + SIGKILL 9 = 137 on Linux)
Both numbers are asserted in ProcessClaimsTest. They are shell conventions for “killed by signal”; other platforms may report different codes, which I did not test.
The hang: the child fills a pipe and waits for a reader who is waiting for the child
The most common ProcessBuilder bug looks like correct code. Start the process, call waitFor(), then read the output. If the child writes more than one pipe-buffer of data, it blocks in write() until someone reads; you are blocked in waitFor() until the child exits. The Javadoc says so in one line: failing to read promptly “may cause the process to block, or even deadlock.”
The sentence under the diagram is the point: this is a deadlock, not a bug in either program, so there is no exception and no log line. The service simply stops. The reproduction below uses a child that writes 200,000 bytes, and it has a 3-second deadline so the demo itself always ends:
From DeadlockDemo.java:
Process p = new ProcessBuilder("sh", "-c", PRODUCE_STDOUT).start();
boolean done = p.waitFor(3, TimeUnit.SECONDS);
System.out.println("child exited within 3s? " + done);
System.out.println("child still alive? " + p.isAlive());
// What the child is stuck on: it wrote ~64 KiB and the pipe is full.
int available = p.getInputStream().available();
System.out.println("bytes sitting in the pipe: " + available);
p.destroyForcibly().waitFor();
Output, from output/02-deadlock.txt. The number in the last line is the pipe buffer on this machine:
== 1. WRONG: waitFor() first, read afterwards
child exited within 3s? false
child still alive? true
bytes sitting in the pipe: 65536
Reading stdout first looks like the fix, and for a child that only writes stdout it is (case 2 in the output file reads all 200,000 bytes and exits 0). But a child that also fills stderr brings the deadlock back, because you are parked on the wrong pipe:
== 3. STILL WRONG: read stdout to EOF, but the child also fills stderr
stdout reader finished within 3s? false
The fingerprint of this bug: a thread stuck in Process.waitFor or in InputStream.read in a thread dump, a child process that is still alive and idle in ps, and a failure that only appears with larger inputs, because small outputs fit in the buffer. “Works in the unit test, hangs on the real file” is exactly this.
There are three fixes, shown in output/02-deadlock.txt. Which one you pick depends on whether you need the output:
== 4. FIX A: merge stderr into stdout, one stream to drain
read 400000 bytes, exit code 0
== 5. FIX B: drain both streams concurrently (what ProcessRunner does)
stdout=200000 stderr=200000 exit=0 timedOut=false
== 6. FIX C: do not pipe at all. Send output to a file or discard it
waitFor() returned immediately with exit code 0
Merge the streams with redirectErrorStream(true) when you do not need stderr separately. One pipe, one reader. You lose the ability to tell error text from output.
Drain both concurrently when you need them separate. That is what the runner in section 4 does with two virtual threads.
Do not use a pipe: Redirect.DISCARD, or a file with redirectOutput(file), when you do not need the bytes in memory. The kernel never blocks the child because there is no reader to wait for.
Going further: where 65,536 comes from, and why the first process you start in a JVM can hide this bug
The available() call in the demo reports 65,536 bytes: that matches the usual Linux default (16 pages of 4 KiB), and it is a property of the OS, not of Java. Other operating systems can use different sizes, which is how a program can pass on one machine and hang on another.
There is also a JDK detail that makes the grandchild case in section 3 confusing to reproduce. When a child exits, ProcessImpl calls a processExited() hook on the stdout and stderr streams, which drains whatever is already in the pipe into memory and lets the file descriptor be reclaimed. In my measurements, the first process started in a fresh JVM was slow enough that this hook ran before my reader had entered read(), and the read returned in 37 ms; every later start blocked for the full 3 seconds. The contract test therefore spawns a throwaway true first. If you benchmark this yourself, warm up, or you will measure the wrong thing.
Evidence: the hook is in the JDK source (ProcessImpl.java, calls at lines 353 and 356 in 25.0.5.1), and the warm-up is in the test aBackgroundGrandchildHoldsAPlainReadHostageButNotTheRunner in ProcessClaimsTest.
For code that already uses futures and timeouts, see the CompletableFuture timeouts post; the same “someone must keep consuming” discipline applies.
Timeouts: waitFor returns false, and nothing has been stopped
A timeout on a child process has two halves, and people write only the first. waitFor(timeout) returns false when time runs out. It does not stop the process; it only stops you waiting. You still have to kill it, and then you have to ask what “it” includes.
From TimeoutDemo.java, output in output/03-timeouts.txt:
Process p = new ProcessBuilder("sleep", "30").start();
System.out.println("waitFor(500ms) = " + p.waitFor(500, TimeUnit.MILLISECONDS));
System.out.println("still alive = " + p.isAlive());
p.destroy(); // SIGTERM
System.out.println("destroy() then waitFor -> exit code " + p.waitFor() + " (128 + SIGTERM 15 = 143)");
== 1. waitFor(timeout) returns false; it does NOT stop the process
waitFor(500ms) = false
still alive = true
destroy() then waitFor -> exit code 143 (128 + SIGTERM 15 = 143)
That settles the direct child. The trouble starts when the child is a shell, because shell commands start more processes:
Left side: you kill the shell and the sleep it started keeps running, now parented to init. Nothing in Java will ever tell you. Right side: take a list of descendants first, while the parent is alive, then kill the parent and the list. The order is the whole trick, and it is the part most snippets get wrong.
Output from output/03-timeouts.txt:
== 2. a shell command spawns a child; destroying the shell orphans it
descendants of the shell: 1 -> [/usr/bin/sleep]
shell dead, orphan alive = true <- leaked process
== 3. kill the tree: snapshot descendants first, then kill all
shell alive = false, former child alive = false
public static void killTree(Process p) throws InterruptedException {
List<ProcessHandle> tree = new ArrayList<>();
p.descendants().forEach(tree::add);
p.destroyForcibly();
tree.forEach(ProcessHandle::destroyForcibly);
p.waitFor(5, TimeUnit.SECONDS);
}
Snapshot before you kill.Process.descendants() walks the live process table. Call it after destroyForcibly() and the children have already been re-parented, so it returns an empty stream (asserted in the tests) and you leak exactly the processes you were trying to stop. A related wrinkle I hit while writing the test: a killed non-child is noticed by polling, so isAlive() immediately afterwards can still say true; wait on onExit() with a bound instead of checking at once.
Going further: a leftover background process can hold your read hostage even after the shell exits
Another way a grandchild bites: it inherits the pipes. sh -c "(sleep 4; echo late) & echo done" exits immediately, but the backgrounded sleep still holds the write end of stdout, so a plain readAllBytes() does not see end-of-file until it finishes. Same command, two ways to read it (from output/03-timeouts.txt):
== 5. a background grandchild keeps the pipe open: readAllBytes() waits for IT
sh exited at once, but readAllBytes() took ~4s; got done|late|
== 6. ProcessRunner is not held hostage by the same command
exit=0 stdout=done| returned in under 2s: true (bounded by the 1s reader grace, not by the 4s grandchild)
The plain read waited roughly the grandchild’s lifetime and returned the late output; the runner gave up after a one-second shared grace period, returned what it had, and tried to close the streams. I tested whether close() unblocks a read already in progress and the answer was not reliable on Linux, so the runner stops waiting rather than depending on it: an abandoned reader stays blocked, and the pipe stays open, until the orphan exits. If you control the command, the robust fix is not to pipe at all (redirect to a file) or to make sure it does not background work.
On JDK 21 or earlier waitFor(Duration) does not exist; use waitFor(long, TimeUnit). In JDK 25 the Duration form is a thin wrapper over the TimeUnit one (JDK source, @since 24).
Put the rules in one place: a runner that drains, caps, closes stdin and enforces a deadline
Every fix so far is one line of a larger discipline. Scattered through a codebase they are forgotten one at a time, so I wrap them once. ProcessRunner.run takes an argument list and returns a result record. The behaviour is the list from the diagrams:
stdout and stderr are drained concurrently, each on its own virtual thread, so no pipe can fill.
Captured output is capped (1 MiB by default). Past the cap the bytes are still read and thrown away, so the child never blocks, and truncated is set.
stdin is closed immediately, so a program that reads input sees end-of-file instead of waiting forever.
On timeout the whole tree is killed, and exitCode is -1 with timedOut true.
The pipe readers get a bounded grace period after the child exits.
public static Result run(List<String> command, Options opt) throws IOException, InterruptedException {
long t0 = System.nanoTime();
ProcessBuilder pb = new ProcessBuilder(command); // argument list: no shell, no injection
pb.environment().putAll(opt.extraEnv());
Process p = pb.start();
p.getOutputStream().close(); // stdin: immediate EOF
Capture out = new Capture(p.getInputStream(), opt.maxCaptureBytes());
Capture err = new Capture(p.getErrorStream(), opt.maxCaptureBytes());
Thread to = Thread.ofVirtual().name("drain-out-" + p.pid()).start(out);
Thread te = Thread.ofVirtual().name("drain-err-" + p.pid()).start(err);
boolean finished = p.waitFor(opt.timeout());
boolean timedOut = !finished;
if (timedOut) {
killTree(p);
}
// Readers normally end at EOF the moment the child exits. If a grandchild inherited the pipes,
// EOF only comes when IT exits, so give the readers one shared grace period, then close the
// streams (best effort: on Linux this does not always interrupt a read already in progress) and
// stop waiting. An abandoned reader stays blocked, and the pipe stays open, until the
// grandchild exits.
long graceEnd = System.nanoTime() + READER_GRACE.toNanos();
joinUntil(to, graceEnd);
joinUntil(te, graceEnd);
if (to.isAlive() || te.isAlive()) {
closeQuietly(p.getInputStream());
closeQuietly(p.getErrorStream());
to.join(Duration.ofMillis(200));
te.join(Duration.ofMillis(200));
}
int exit = timedOut ? -1 : p.exitValue();
return new Result(exit, out.text(), err.text(), timedOut,
out.truncated || err.truncated, Duration.ofNanos(System.nanoTime() - t0));
}
== 5. FIX B: drain both streams concurrently (what ProcessRunner does)
stdout=200000 stderr=200000 exit=0 timedOut=false
== 4. ProcessRunner with a deadline
timedOut=true exit=-1 stdout=started elapsed<2s=true
The stdin rule deserves its own example, because it fails in the opposite direction: nothing is too big, the child is just waiting. cat reads standard input until end-of-file, and end-of-file only arrives when you close your end:
From EnvironmentDemo.java, output in output/04-environment.txt:
Process cat = new ProcessBuilder("cat").start();
try (var w = cat.outputWriter()) {
w.write("line one\nline two\n");
} // closing the writer closes the child's stdin
System.out.println("cat echoed: " + new String(cat.getInputStream().readAllBytes()).replace("\n", " | ")
+ " exit " + cat.waitFor());
== 6. stdin: close it, or a reader like cat never sees EOF
cat echoed: line one | line two | exit 0
Going further: the runner, read line by line
new ProcessBuilder(command) with a List is the injection defence, covered in section 7.
p.getOutputStream().close() directly after start() is the stdin rule. If you need to feed input, write it first, then close.
Two Capture runnables on Thread.ofVirtual(): virtual threads are cheap to create, so two readers per child cost little to start. A blocking pipe read may still occupy a carrier thread while it waits; I did not measure that under load, so test it before running thousands of children at once.
p.waitFor(opt.timeout()) returns false on timeout, which routes to killTree.
Shared grace deadline (joinUntil) so two blocked readers cost one second, not one each. My first version joined them one after the other and a grandchild case took 4 seconds instead of 1.4; the fix is in the repo.
What it deliberately does not do: no output streaming to a callback, no merged stream, no Windows handling, and no retry. Add those when you need them; do not start there.
Environment, working directory and redirects: configuration that changes what the child sees
Before start() you can change three things about the world the child wakes up in. The first surprise is that pb.environment() is a copy of your environment, so changing it never affects your own JVM:
From EnvironmentDemo.java, output in output/04-environment.txt:
ProcessBuilder pb = new ProcessBuilder("sh", "-c", "echo GREETING=$GREETING MODE=$MODE");
pb.environment().put("GREETING", "hello");
System.out.println("child sees : " + run(pb));
System.out.println("our own env: GREETING=" + System.getenv("GREETING") + " (unchanged)");
== 1. the child inherits a COPY of our environment
child sees : GREETING=hello MODE=
our own env: GREETING=null (unchanged)
== 2. clear() and rebuild: pass only what the child needs
child sees : HOME=[] PATH=[/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin] MODE=[minimal]
clear() is the right starting point when the command is untrusted or you want reproducible behaviour: pass only what the child needs. Note what the output shows for PATH after a clear: the shell supplied its own default. That is the shell’s doing, not Java’s, and it leads to the next trap.
Which PATH finds the program? The one in your JVM, not the one you put in pb.environment(). The output below shows date starting fine with the child’s PATH set to a directory that does not exist, while sh -c "date +%Y" then fails because the shell resolves date with the child’s PATH. If a command works from a unit test and fails under a service manager with a stripped environment, this is the first place to look.
== 3. which PATH finds the program? start() uses OURS; the child's PATH is for the child
start("date") with child PATH=/nonexistent : true (resolved with the parent's PATH)
sh -c 'date +%Y' with child PATH=/nonexistent : sh: 1: date: not found
Working directory and redirection are simpler. directory(File) sets where the child starts, and a directory that does not exist surfaces as the same IOException as a missing program, with the directory named in the message. Redirecting to a file removes the pipe, so there is nothing to drain:
Output from output/04-environment.txt:
== 4. working directory
ls in temp dir: marker.txt
bad directory -> IOException: Cannot run program "ls" (in directory "/no/such/dir"): Exec failed, error: 2 (No such file or directory)
== 5. redirect to files: no pipe, so nothing to drain
exit 0, file contains: to-stdout | to-stderr |
getInputStream() on a redirected process is a null stream: read() = -1
Going further: inheritIO, appendTo, and reading a redirected streaminheritIO() wires the child to your own stdin, stdout and stderr: right for a CLI tool that wraps another, wrong for a server, where the child’s output lands in whatever your process manager does with stdout. Redirect.appendTo(file) keeps a log across runs. When a stream is redirected, getInputStream() returns a null stream: the last line of the output above shows read() = -1 immediately, so reading it is harmless but pointless. Redirects are the one fix that needs no reader at all.
ProcessHandle: PIDs, onExit() and pipelines without a shell
Process is the object you got from start(). ProcessHandle (Java 9+) describes any process by PID, including your own and ones you did not start. Its most useful method for service code is onExit(), a CompletableFuture that completes when the process ends, so you can react without parking a thread:
From HandleDemo.java, output in output/05-handles.txt:
Process p = new ProcessBuilder("sh", "-c", "sleep 1; exit 3").start();
CompletableFuture<Void> done = p.onExit().thenAccept(proc ->
System.out.println("callback: exited with " + proc.exitValue()));
System.out.println("main thread is free; alive = " + p.isAlive());
== 2. onExit() instead of a blocked thread
main thread is free; alive = true
callback: exited with 3
== 3. what ProcessHandle.Info reveals about a child
command = /usr/bin/sleep
arguments = 5
user set = true, startInstant set = true
info() reports the command, arguments, user and start time where the OS allows it; each field is an Optional because platforms and permissions differ. The last case is the answer to “I need a | b | c”. ProcessBuilder.startPipeline connects the stages directly, with no shell and therefore no injection surface. From HandleDemo.java:
List<Process> procs = ProcessBuilder.startPipeline(List.of(
new ProcessBuilder("printf", "b\\na\\nb\\nc\\nb\\n"),
new ProcessBuilder("sort"),
new ProcessBuilder("uniq", "-c")));
Process last = procs.get(procs.size() - 1);
System.out.print(new String(last.getInputStream().readAllBytes()));
for (Process x : procs) x.waitFor();
== 5. a real pipeline without a shell: printf | sort | uniq -c
1 a
3 b
1 c
stages: 3
Going further: what startPipeline does with stderr and the last stage
Only the last process’s stdout is yours to read (procs.get(procs.size() - 1)); every earlier stage’s stdout feeds the next one. Stderr of each stage is still a pipe you must drain or redirect, so the deadlock rules from section 2 apply per stage. I did not test a pipeline with very large stderr output.
Injection: the shell is the vulnerability, and arguments have a version of it too
If any part of the command comes from outside your code (a filename, a form field, a model’s tool call), command injection is the risk that matters more than any hang. The classic version needs a shell: building "wc -c " + userInput and handing it to sh -c lets the input end the command and start another.
From InjectionDemo.java, output in output/06-injection.txt. The first block is the vulnerable one; the second is the same input as a single argument:
== 1. VULNERABLE: build a shell string from user input
$ sh -c wc -c report.txt; cat secret.txt
18 report.txt
TOP-SECRET [exit 0]
== 2. SAFE: argument list, no shell. The whole input is one filename
$ wc -c report.txt; cat secret.txt
wc: 'report.txt; cat secret.txt': No such file or directory [exit 1]
In the vulnerable run secret.txt was printed: the input smuggled in a second command. With an argument list there is no shell to interpret ;, so the whole string is one filename and wc reports that no such file exists. That is the defence: pass an argument list, never a concatenated string, and avoid sh -c with data in it.
An argument list is not the end of it. If the input is -l, ls treats it as an option, not a filename, because the program parses its own arguments. This is option injection, and it needs no shell at all. The output shows the listing leaking secret.txt; putting -- before user data ends option parsing, and an allow-list rejects the dangerous inputs before they reach any command.
== 3. SAFE but still a trap: option injection. Input '-l' is read as a flag
$ ls -l
total 8
-rw-r--r-- 1 root root 18 Nov 26 00:48 report.txt
-rw-r--r-- 1 root root 11 Nov 26 00:48 secret.txt [exit 0]
(the caller wanted to list a file called '-l'; ls took it as an option)
== 4. FIX: '--' ends option parsing, then validate
$ ls -- -l
ls: cannot access '-l': No such file or directory [exit 2]
== 5. FIX: allow-list the input before it gets anywhere near a command
'report.txt' -> true
'report.txt; cat secret.txt' -> false
'-l' -> false
'../etc/passwd' -> false
Going further: what an allow-list should and should not be
The safeName check in the demo is deliberately narrow: it starts with a letter or digit (so no leading dash), allows only letters, digits, dot and underscore, and caps the length. That is a validation of one specific input, not a general sanitiser. The point of an allow-list is that it describes what is accepted, so a new attack shape is rejected by default; a deny-list of bad characters is the pattern that keeps being bypassed. For a broader treatment see the OWASP OS command injection defence cheat sheet. If you are weighing the same trade-off for deserialisation, the Java serialization post reaches the same “do not interpret untrusted input as code” conclusion from a different direction.
Should you shell out at all? Often not. If a Java API does the job (java.nio.file.Files for file operations, java.util.zip for archives, HttpClient for HTTP), use it: no pipes, no PATH, no injection, and the same behaviour on every OS. Shell out when the program is the point (ffmpeg, git, a vendor CLI) and then do it with the runner above. Never build the command line from untrusted text if an argument list or a fixed command can do the job instead. And if an AI agent chooses the command, treat its output as untrusted input: allow-list the program, not just the arguments. I have only verified Linux behaviour here; if you ship on Windows, test the quoting and exit codes there.
The 14 contract tests behind the claims
Every behavioural claim in the post is an assertion in ProcessClaimsTest, and the run is committed as output/07-tests.txt:
Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 16.26 s -- in com.ankurm.process.ProcessClaimsTest
The tests that involve timing (pipe stuck for 2 seconds, grandchild holds a read for about 3) assert generous bounds, not exact numbers. Outputs in the post that contain PIDs or timings are indicative; the behaviour they show is what the tests pin.
No Comments yet!