ProcessBuilder Argument List Execution

Run external commands safely through ProcessBuilder argument lists with streamed output, a hard timeout, and destroyForcibly cleanup.

JavaSecurity Boundaries

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SafeCommand {

    public static void main(String[] args) throws Exception {
        Path workdir = Files.createTempDirectory("safe-cmd");

        // 参数以 List 传递:不经 shell 解析,用户输入无法注入额外命令
        List<String> command = List.of("git", "-C", workdir.toString(), "init", "--quiet");

        Process process = new ProcessBuilder(command)
                .redirectErrorStream(true)
                .directory(workdir.toFile())
                .start();

        boolean finished = process.waitFor(10, TimeUnit.SECONDS);
        if (!finished) {
            process.destroyForcibly();
            process.waitFor();
            throw new IllegalStateException("command timed out: " + command.get(0));
        }

        String output = new String(process.getInputStream().readAllBytes());
        System.out.println("exit=" + process.exitValue());
        if (!output.isBlank()) {
            System.out.println(output.strip());
        }
    }
}

How it works

Count the class SafeCommand as the entire surface area of ProcessBuilder Argument List Execution.

Invalid states are rejected up front: it throws IllegalStateException instead of continuing with bad data.

Putting it to use

The demo output is labeled (exit=), so every printed line maps back to its originating operation.

Core lines

throw new IllegalStateException("command timed out: " + command.get(0));

Interactive Tools for This Topic

FAQ

What happens on invalid input?
It throws `IllegalStateException` before any real work runs — handle it at the call site or let it propagate deliberately.
What does ProcessBuilder Argument List Execution print when run?
Running the file directly is enough — expect labeled output lines such as `exit=`.