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

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_spawn or fork plus exec; on Windows with CreateProcess. The child gets three standard streams, and by default each one is connected to the JVM through an operating system pipe:

  • the child's standard input is process.getOutputStream(): what Java writes, the child reads;
  • 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 passes each argument directly to the program, while a shell, if you start one, interprets quotes, semicolons and $ in its input.

The process APIs
APISinceBest for
Runtime.exec(String)Java 1.0; deprecated in Java 18Nothing in new code: it splits the string at spaces
ProcessBuilderJava 5Starting programs with arguments, directory, environment and redirects
Redirect.DISCARD, ProcessBuilder.startPipelineJava 9Ignoring output; chaining programs without a shell
ProcessHandleJava 9 (JEP 102)Inspecting, waiting for and stopping any process, including the JVM itself
Process.inputReader, outputWriter, errorReaderJava 17Text I/O with the child without wrapping streams by hand

The examples ran on JDK 21 on Linux and call standard Unix commands (ls, sort, sh); on Windows the same Java code works with Windows programs.

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.

Java
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:

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
  1. ls -1 /usr/bin is three list items, not one string. The program read all lines and only then called waitFor(), which returned exit code 0.
  2. The shell script ran in a temporary directory with GREETING=hello added to the inherited environment. redirectErrorStream(true) merged the error message of the failing ls 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.
  3. sort 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.
  4. waitFor(200, MILLISECONDS) returned false for a 10-second sleep, and destroyForcibly() killed it. destroy() asks politely (SIGTERM on Unix), destroyForcibly() does not (SIGKILL).
  5. startPipeline connected ls, grep and wc directly, each one's output to the next one's input, without a shell.

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.

Java
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:

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
  1. 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 waitFor(), both would wait forever.
  2. redirectErrorStream(true) merged both streams into one, which the parent read to the end: 200,007 bytes, the 7-byte result line plus the warnings.
  3. Reading stderr on another thread while reading stdout on this one keeps both pipes drained and the two streams separate.
  4. Redirect.DISCARD sends stderr to the null device, so it can never fill up. Redirecting to a file with Redirect.to works the same way and keeps the text.

The rule: every stream of a child must be read, redirected or discarded, and waitFor() should come after the reading is done.

Command injection: why arguments beat a shell

A user supplies a file name that contains shell syntax. The program passes it once through sh -c and once as a plain argument, then shows how ProcessBuilder treats spaces, quotes and $.

Java
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:

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 sh -c, the semicolon ended the first command and the shell ran the attacker's second one: "INJECTED COMMAND RAN". With a real command instead of echo, that is remote code execution.
  • As a separate argument, the same text reached echo unchanged, semicolon and all. No shell parsed it, so nothing was executed.
  • Each list element is exactly one argument: "two words" stayed together, the single quotes were passed literally, and $HOME was not expanded. Quoting rules only exist when a shell is involved.
  • If a shell is unavoidable, pass user data as positional parameters, sh -c 'grep -- "$1" file' sh "$input", 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.

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.

Java
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:

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
  1. Redirect.appendTo(file) made two runs write to the same log; the bytes went from the child straight to the file. Redirect.to(file) truncates instead.
  2. redirectInput(file) connected the file to sort's standard input. inputReader() (Java 17) wraps the output stream in a BufferedReader using the native charset; pass a charset to it when the child's encoding differs.
  3. outputWriter() gives a BufferedWriter on the child's input. Closing it sent end of file, so tr finished and printed "HELLO PROCESS".
  4. inheritIO() 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.

ProcessHandle: inspecting and watching processes

ProcessHandle (Java 9) represents any process on the machine by its process id, not only children started from Java. The program inspects the JVM itself, starts a sleep, checks the parent and child relationship, and registers a callback for the child's end.

Java
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:

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
  • ProcessHandle.current() is the JVM itself; info() gives the command, arguments, start time and user when the operating system allows reading them, which is why each value is an Optional.
  • The child's parent was this JVM, and children() found it. descendants() also includes grandchildren, which matters because destroy() on a shell does not stop the programs the shell started.
  • onExit() returns a CompletableFuture completed when the process ends, so the program can react without a thread blocked in waitFor().
  • The exit value 143 is 128 + 15: on Unix a process killed by signal 15 (SIGTERM, sent by destroy()) reports 128 plus the signal number.

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() to the end of waitFor(), best of 3 rounds; a rough comparison.

Java
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):

Output
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 true, a program that does nothing, took on the order of a millisecond or two to start and finish, and starting it through sh -c cost about the same here. Calling a program per item in a loop over thousands of items costs seconds.
  • Starting another JVM took tens of milliseconds, even for -version. 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, java.util.spi.ToolProvider runs javac, jar and others inside the current JVM.

Choosing how to run a process

Process recipes
SituationUse
Run a program with argumentsnew ProcessBuilder("prog", arg1, arg2), never a concatenated string
Read output and errors togetherredirectErrorStream(true), read everything, then waitFor()
Ignore output safelyRedirect.DISCARD
Keep output in a log fileRedirect.to or Redirect.appendTo
Avoid hanging foreverwaitFor(timeout, unit), then destroy() or destroyForcibly()
Chain programsProcessBuilder.startPipeline
React when a process endsprocess.onExit() or ProcessHandle.onExit()
Run JDK toolsToolProvider, in-process

See buffered streams for reading process output efficiently and charsets for decoding it correctly.