Java Processes and ProcessBuilder: Running and Managing External Programs
Run external programs from Java with ProcessBuilder and Process: commands and working directories, stdin/stdout/stderr pipes, redirects, environment variables, pipelines, exit codes, timeouts, destroy, onExit and inspecting any OS process with ProcessHandle.
kvi5hnuCode Sprout team member10 min readOn this page
So far, everything concurrent happened in threads inside one JVM. Sometimes you need to run another program: a compiler, git, a database dump tool, an image converter or a script. Java does this with two classes. ProcessBuilder configures a new operating system process, and Process lets you talk to it through its standard input, output and error, wait for it, and kill it. ProcessHandle goes further and lets you inspect any process on the machine.
ProcessBuilder is the flexible, modern replacement for the old Runtime.getRuntime().exec(...) calls. Some exec overloads that took a single command string were deprecated in Java 18, because splitting a string into arguments is error-prone.
Building a process
Specify the command as separate strings or as a List<String>. The first element is the program, and each following element is one argument:
var builder = new ProcessBuilder("gcc", "myapp.c");
Every process has a working directory for resolving relative paths. By default it's the JVM's, typically the directory from which you launched java. Change it with directory:
builder = builder.directory(path.toFile());
All configuration methods return the builder, so you can chain them and finish with start():
Process p = new ProcessBuilder(command).directory(file).inheritIO().start();
Standard streams
By default, the process's standard input, output and error are pipes that you access through the Process object:
OutputStream processIn = p.getOutputStream();
InputStream processOut = p.getInputStream();
InputStream processErr = p.getErrorStream();
For text, Java 17 added readers and writers, optionally with a Charset:
BufferedWriter processIn = p.outputWriter();
BufferedReader processOut = p.inputReader();
BufferedReader processErr = p.errorReader();
The names are from the JVM's point of view, which confuses everyone at first. The process's input is an output stream for you. Whatever you write there, the process reads. The process's output and error are input streams that you read.

Instead of pipes, you can connect the streams elsewhere:
builder.inheritIO()makes all three streams the same as the JVM's. Keyboard input reaches the process, and its output appears in your console. For individual streams, passProcessBuilder.Redirect.INHERITtoredirectInput,redirectOutputorredirectError.- Files:
builder.redirectInput(inputFile).redirectOutput(outputFile).redirectError(errorFile). Output and error files are created or truncated when the process starts. To append, useRedirect.appendTo(file). Redirect.DISCARD(Java 9) throws the output away, like/dev/null.builder.redirectErrorStream(true)merges error into output, so messages appear in the order they were produced. After that, you can't useredirectErrororgetErrorStream, because there's nothing separate left.
Environment variables
The builder's environment starts as a copy of the JVM's. Here the chaining style breaks down: you get the mutable map and edit it before start():
Map<String, String> env = builder.environment();
env.put("LANG", "fr_FR");
env.remove("JAVA_HOME");
Process p = builder.start();
Removing variables the child shouldn't see, such as credentials, is good practice.
Pipelines
To pipe one process's output into the next process's input, as with | in a shell, use startPipeline (Java 9). It returns all the processes, and you read the result from the last one. For example, here is how you would list the distinct file extensions in a directory tree:
List<Process> processes = ProcessBuilder.startPipeline(List.of(
new ProcessBuilder("find", "/opt/jdk-21"),
new ProcessBuilder("grep", "-o", "\\.[^./]*$"),
new ProcessBuilder("sort"),
new ProcessBuilder("uniq")));
Process last = processes.getLast();
String result = new String(last.getInputStream().readAllBytes());
Of course, walking the directory in Java with Files.walk would be far more efficient than starting four processes. Reach for external programs only when you really need them.
Running a process
Once started, you write to the input and read the output and error:
Process process = new ProcessBuilder("/bin/ls", "-l")
.directory(Path.of("/tmp").toFile())
.start();
try (var in = new Scanner(process.getInputStream())) {
while (in.hasNextLine())
System.out.println(in.nextLine());
}
Close the process's input stream when you're done writing. That's how the child sees end of input.
Waiting, exit codes and killing
int result = process.waitFor(); // blocks; returns the exit value
By convention, exit value 0 means success and nonzero values are error codes. To avoid waiting forever:
if (process.waitFor(delay, TimeUnit.SECONDS)) {
int result = process.exitValue();
...
} else {
process.destroyForcibly();
}
The timed waitFor returns true if the process exited in time. Then get the code with exitValue(), which throws IllegalThreadStateException if the process is still running.
You don't have to wait at all. Leave the process running and check isAlive() now and then. To stop it, call destroy() or destroyForcibly(). What they do depends on the platform. On Unix, destroy sends SIGTERM, which the program may catch to clean up, and destroyForcibly sends SIGKILL, which can't be caught. supportsNormalTermination() tells you whether destroy can end the process gracefully.
For an asynchronous notification, onExit() returns a CompletableFuture<Process> (article 102):
process.onExit().thenAccept(p -> System.out.println("Exit value: " + p.exitValue()));
Since Java 21, the System.Logger named java.lang.ProcessBuilder logs every process started by ProcessBuilder or Runtime.exec. At DEBUG level it logs the pid, directory and command, and at TRACE level it also logs the arguments, along with a stack trace. That's useful for auditing what an application runs.
Process handles
The ProcessHandle interface (Java 9) describes a process: one you started, or any other process on the machine. There are four ways to get one:
p.toHandle()for aProcessyou started.ProcessHandle.of(pid)for an operating system process id. It returns anOptional.ProcessHandle.current()for the JVM's own process.ProcessHandle.allProcesses()for aStreamof every process visible to you.
From a handle you can navigate the process tree:
long pid = handle.pid();
Optional<ProcessHandle> parent = handle.parent();
Stream<ProcessHandle> children = handle.children();
Stream<ProcessHandle> descendants = handle.descendants();
The streams from allProcesses, children and descendants are snapshots. By the time you look, some processes may have exited and others may have started.
handle.info() returns a ProcessHandle.Info with arguments(), command(), commandLine(), startInstant(), totalCpuDuration() and user(). All of them return Optionals, because not every OS reports everything and you may lack permission. For example, here is how to list the command lines of all running Java processes:
ProcessHandle.allProcesses()
.map(ProcessHandle::info)
.filter(info -> info.command().filter(s -> s.endsWith("/java")).isPresent())
.forEach(info -> info.commandLine().ifPresent(System.out::println));
For monitoring and termination, ProcessHandle has the same isAlive, supportsNormalTermination, destroy, destroyForcibly and onExit methods as Process. There is no waitFor, so use onExit().join() instead. You can only destroy processes you're allowed to, and you can never destroy the current process through its handle.
A complete example
To work on every operating system, the demo writes a small helper program Child.java to a temporary directory and runs it with the same java launcher in source-file mode (java Child.java mode). That means the children are real OS processes. The demo pipes text in and reads stdout and stderr, checks an exit code, merges the streams, sets environment variables and a working directory, redirects from and to files (including append), and builds a two-process pipeline. Finally it times out a sleeping child, inspects it through ProcessHandle, kills it and gets notified via onExit. Process ids differ from run to run, so the demo prints only facts about them.
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
public class Solution {
// A small helper program that the demo runs as a separate operating system process.
static final String CHILD = """
import java.io.*;
import java.nio.file.*;
public class Child {
public static void main(String[] args) throws Exception {
var in = new BufferedReader(new InputStreamReader(System.in));
switch (args[0]) {
case "upper" -> {
String line;
while ((line = in.readLine()) != null) System.out.println(line.toUpperCase());
System.err.println("upper: done");
}
case "count" -> System.out.println("lines: " + in.lines().count());
case "mixed" -> {
System.out.println("out 1"); System.out.flush();
System.err.println("err 1"); System.err.flush();
Thread.sleep(100);
System.out.println("out 2"); System.out.flush();
}
case "env" -> System.out.println("GREETING=" + System.getenv("GREETING")
+ ", DEMO_SECRET set: " + (System.getenv("DEMO_SECRET") != null));
case "pwd" -> System.out.println("working dir: " + Path.of("").toAbsolutePath().getFileName());
case "fail" -> { System.err.println("something went wrong"); System.exit(3); }
case "sleep" -> Thread.sleep(60_000);
default -> System.exit(64);
}
}
}
""";
static Path dir;
static String java = Path.of(System.getProperty("java.home"), "bin", "java").toString();
static ProcessBuilder child(String mode) {
return new ProcessBuilder(java, dir.resolve("Child.java").toString(), mode);
}
public static void main(String[] args) throws Exception {
dir = Files.createTempDirectory("procdemo");
Files.writeString(dir.resolve("Child.java"), CHILD);
System.out.println("-- pipes: write to its input, read its output and error --");
Process p = child("upper").start();
try (BufferedWriter toChild = p.outputWriter()) { // the process's stdin
toChild.write("hello\nprocess world\n");
} // closing it sends end of input
try (BufferedReader fromChild = p.inputReader();
BufferedReader errors = p.errorReader()) {
// reading stdout and then stderr in one thread is safe here only because the child
// writes very little; see the deadlock callout above
fromChild.lines().forEach(l -> System.out.println(" stdout: " + l));
errors.lines().forEach(l -> System.out.println(" stderr: " + l));
}
System.out.println(" exit value: " + p.waitFor());
System.out.println("-- exit codes --");
Process failing = child("fail").redirectError(ProcessBuilder.Redirect.DISCARD).start();
System.out.println(" waitFor() = " + failing.waitFor() + " (nonzero means failure)");
System.out.println("-- merging stderr into stdout --");
Process mixed = child("mixed").redirectErrorStream(true).start();
System.out.println(" " + new String(mixed.getInputStream().readAllBytes()).lines().toList());
mixed.waitFor();
System.out.println("-- environment and working directory --");
var envBuilder = child("env");
Map<String, String> env = envBuilder.environment(); // starts as a copy of ours
env.put("GREETING", "bonjour");
env.remove("DEMO_SECRET");
Process envProc = envBuilder.start();
System.out.println(" " + new String(envProc.getInputStream().readAllBytes()).strip());
envProc.waitFor();
Path work = Files.createDirectories(dir.resolve("workdir"));
Process pwd = child("pwd").directory(work.toFile()).start();
System.out.println(" " + new String(pwd.getInputStream().readAllBytes()).strip());
pwd.waitFor();
System.out.println("-- redirecting to and from files --");
Path input = Files.writeString(dir.resolve("in.txt"), "alpha\nbeta\n");
Path output = dir.resolve("out.txt");
child("upper").redirectInput(input.toFile()).redirectOutput(output.toFile())
.redirectError(ProcessBuilder.Redirect.DISCARD).start().waitFor();
child("upper").redirectInput(input.toFile())
.redirectOutput(ProcessBuilder.Redirect.appendTo(output.toFile()))
.redirectError(ProcessBuilder.Redirect.DISCARD).start().waitFor();
System.out.println(" out.txt after write + append: " + Files.readAllLines(output));
System.out.println("-- a pipeline: upper | count --");
List<Process> pipeline = ProcessBuilder.startPipeline(List.of(
child("upper").redirectInput(input.toFile()).redirectError(ProcessBuilder.Redirect.DISCARD),
child("count")));
Process last = pipeline.getLast();
System.out.println(" " + new String(last.getInputStream().readAllBytes()).strip()
+ " (" + pipeline.size() + " processes)");
for (Process q : pipeline) q.waitFor();
System.out.println("-- timeouts, destroy and onExit --");
Process sleeper = child("sleep").start();
CompletableFuture<Process> exited = sleeper.onExit();
boolean finished = sleeper.waitFor(300, TimeUnit.MILLISECONDS);
System.out.println(" finished within 300 ms: " + finished + ", alive: " + sleeper.isAlive());
ProcessHandle handle = sleeper.toHandle();
System.out.println(" child's parent is this JVM: "
+ handle.parent().map(ProcessHandle::pid).orElse(-1L).equals(ProcessHandle.current().pid()));
System.out.println(" this JVM's children include it: "
+ ProcessHandle.current().children().anyMatch(h -> h.pid() == sleeper.pid()));
System.out.println(" info().command() present: " + handle.info().command().isPresent());
if (!finished) sleeper.destroyForcibly();
Process gone = exited.get(10, TimeUnit.SECONDS);
System.out.println(" onExit completed, alive: " + gone.isAlive() + ", exit value nonzero: " + (gone.exitValue() != 0));
System.out.println("-- this JVM's own handle --");
ProcessHandle me = ProcessHandle.current();
System.out.println(" pid > 0: " + (me.pid() > 0) + ", alive: " + me.isAlive()
+ ", command ends with java: " + me.info().command().map(c -> c.endsWith("java") || c.endsWith("java.exe")).orElse(true));
long javaProcesses = ProcessHandle.allProcesses()
.filter(h -> h.info().command().map(c -> c.contains("java")).orElse(false)).count();
System.out.println(" visible Java processes >= 1: " + (javaProcesses >= 1));
try (var files = Files.walk(dir)) {
files.sorted(Comparator.reverseOrder()).forEach(f -> f.toFile().delete());
}
}
}
-- pipes: write to its input, read its output and error --
stdout: HELLO
stdout: PROCESS WORLD
stderr: upper: done
exit value: 0
-- exit codes --
waitFor() = 3 (nonzero means failure)
-- merging stderr into stdout --
[out 1, err 1, out 2]
-- environment and working directory --
GREETING=bonjour, DEMO_SECRET set: false
working dir: workdir
-- redirecting to and from files --
out.txt after write + append: [ALPHA, BETA, ALPHA, BETA]
-- a pipeline: upper | count --
lines: 2 (2 processes)
-- timeouts, destroy and onExit --
finished within 300 ms: false, alive: true
child's parent is this JVM: true
this JVM's children include it: true
info().command() present: true
onExit completed, alive: false, exit value nonzero: true
-- this JVM's own handle --
pid > 0: true, alive: true, command ends with java: true
visible Java processes >= 1: true
Common questions
Why doesn't new ProcessBuilder("ls *.txt") work?
There is no shell. The builder looks for a program literally named ls *.txt. Pass the program and its arguments as separate strings, and if you really need wildcards or pipes, run "/bin/sh", "-c", "...", never with untrusted input in the string.
Why does my program hang when the child process produces a lot of output?
The pipe between the processes has a small buffer. If you don't read the child's output or error stream, the child blocks once the buffer is full, and waitFor never returns. Read both streams, merge them with redirectErrorStream(true), or redirect them to files or Redirect.DISCARD.
Runtime.exec or ProcessBuilder?
ProcessBuilder. It lets you set the working directory, environment and redirections, and takes arguments as a list. The exec(String) overloads that split a command string are deprecated since Java 18.
How do I find out the PID of a process?
process.pid() for a process you started, and ProcessHandle.current().pid() for the JVM itself. ProcessHandle.info() gives the command line, start time and user where the OS provides them.
How do I avoid waiting forever for a child process?
Use waitFor(timeout, unit), which returns false if the process is still running. Then call destroy(), and destroyForcibly() if it still doesn't exit. onExit() returns a CompletableFuture if you'd rather be notified than wait.
API reference
java.lang.ProcessBuilder
| Method | Description |
|---|---|
ProcessBuilder(String... command), ProcessBuilder(List<String> command) | command and arguments; the first element is the executable |
ProcessBuilder directory(File dir) | working directory of the process |
ProcessBuilder inheritIO() | use the JVM's stdin, stdout and stderr (Java 7) |
ProcessBuilder redirectErrorStream(boolean merge) | merge stderr into stdout |
redirectInput(File), redirectOutput(File), redirectError(File) | connect a stream to a file (Java 7) |
redirectInput/Output/Error(ProcessBuilder.Redirect r) | Redirect.PIPE (default), INHERIT, DISCARD, from(file), to(file), appendTo(file) |
Map<String, String> environment() | mutable copy of the environment for the new process |
Process start() | starts the process |
static List<Process> startPipeline(List<ProcessBuilder> builders) | connects each process's stdout to the next one's stdin (Java 9) |
java.lang.Process
| Method | Description |
|---|---|
OutputStream getOutputStream(), BufferedWriter outputWriter() | write to the process's standard input |
InputStream getInputStream(), BufferedReader inputReader() | read the process's standard output |
InputStream getErrorStream(), BufferedReader errorReader() | read the process's standard error |
int waitFor(), boolean waitFor(long timeout, TimeUnit unit) | wait for exit; exit value, or true if it exited in time |
int exitValue() | exit value; nonzero conventionally means failure |
boolean isAlive(), long pid() | status and process id |
void destroy(), Process destroyForcibly(), boolean supportsNormalTermination() | terminate normally (SIGTERM) or forcibly (SIGKILL) |
ProcessHandle toHandle(), CompletableFuture<Process> onExit() | handle; asynchronous exit notification |
java.lang.ProcessHandle and ProcessHandle.Info
| Method | Description |
|---|---|
static Optional<ProcessHandle> of(long pid), static ProcessHandle current(), static Stream<ProcessHandle> allProcesses() | obtain handles |
long pid(), Optional<ProcessHandle> parent(), Stream<ProcessHandle> children(), descendants() | identity and process tree (snapshots) |
ProcessHandle.Info info() | details: arguments(), command(), commandLine(), startInstant(), totalCpuDuration(), user(), all Optional |
isAlive(), destroy(), destroyForcibly(), supportsNormalTermination(), onExit() | monitoring and termination (no waitFor) |
Summary
ProcessBuilderconfigures a process: the command and arguments (no shell), working directory, stream redirection (pipe, inherit, file, append, discard, merged error) and environment.start()runs it, andstartPipelinechains processes.Processstreams are named from the JVM's side. You write to its input and read its output and error. Read promptly and drain both output streams to avoid deadlocks on full pipes.waitForreturns the exit code (0 means success). The timedwaitFor,isAlive,destroy/destroyForciblyandonExithandle long-running or stuck processes.ProcessHandleinspects the current, child or any visible process: pid, parent, children, descendants andInfodetails, all as snapshots andOptionals.
Practice Questions
Why doesn't new ProcessBuilder("ls *.txt").start() list text files?
There are two problems. The whole string is treated as the program name, so the arguments must be separate strings, and no shell expands *. Use new ProcessBuilder("ls") and filter in Java, or explicitly run a shell: new ProcessBuilder("/bin/sh", "-c", "ls *.txt").
Which Process method do you use to send data to the program's standard input, and why is its name surprising?
getOutputStream() or outputWriter(). From the JVM's point of view, you write to that stream, so it's an output stream, even though it becomes the program's input. Close it when you're done so the program sees end of input.
A program hangs while reading a child process's standard output. The child writes many warnings to standard error. What's going on?
The child filled the small stderr pipe buffer and is blocked writing to it, because nobody reads stderr. Meanwhile your program waits for more stdout. Read both streams concurrently, merge them with redirectErrorStream(true), or redirect stderr to a file or DISCARD.
How do you wait at most 5 seconds for a process and kill it otherwise?
Use if (!p.waitFor(5, TimeUnit.SECONDS)) p.destroyForcibly(); and, if it finished in time, read p.exitValue().
What is the difference between Process and ProcessHandle?
A Process represents a process you started, with access to its standard streams and waitFor. A ProcessHandle can describe any visible process, including the current JVM, its parent and its children, and offers information and termination, but it has no stream access and no waitFor (use onExit() instead).
Previous: Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
Next: Java Annotations Explained: Syntax, Uses and Where You Can Annotate
Related reading
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
- Java Primitive Types: Integers and Floating-Point Numbers Explained

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.