process-api: ProcessBuilder and Process API module (pipe-buffer deadlock and its fixes, timeouts and process-tree kill, grandchild holding the pipe, environment/redirect/stdin, ProcessHandle, startPipeline, shell and option injection), ProcessRunner, 14 contract tests
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b3W3uHbHAmM3orhn7b
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
47e4ccbefa
commit
a714780bca
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.process;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** The smallest correct use of ProcessBuilder, and the first three things that go wrong. */
|
||||
public final class BasicsDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("== 1. the smallest thing that works");
|
||||
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);
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. a failing command is NOT an exception: it is a non-zero exit code");
|
||||
Process f = new ProcessBuilder("ls", "/definitely/not/here").start();
|
||||
String err = new String(f.getErrorStream().readAllBytes()).strip();
|
||||
System.out.println("stderr = " + err);
|
||||
System.out.println("exit code = " + f.waitFor());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. a command that does not exist IS an exception, thrown by start()");
|
||||
try {
|
||||
new ProcessBuilder("no-such-binary-xyz").start();
|
||||
} catch (IOException e) {
|
||||
System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. exitValue() before the process ends throws");
|
||||
Process sleeper = new ProcessBuilder("sleep", "5").start();
|
||||
try {
|
||||
sleeper.exitValue();
|
||||
} catch (IllegalThreadStateException e) {
|
||||
System.out.println("IllegalThreadStateException: " + e.getMessage());
|
||||
}
|
||||
System.out.println("waitFor(200ms) returned " + sleeper.waitFor(200, TimeUnit.MILLISECONDS)
|
||||
+ " (false = still running, true = exited)");
|
||||
sleeper.destroyForcibly().waitFor();
|
||||
System.out.println("after destroyForcibly(): exit code = " + sleeper.exitValue()
|
||||
+ " (128 + SIGKILL 9 = 137 on Linux)");
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 5. the shell is not involved: no pipes, no globs, no $VARS");
|
||||
Process g = new ProcessBuilder(List.of("echo", "*.txt", "$HOME", "a|b")).start();
|
||||
System.out.println("stdout = " + new String(g.getInputStream().readAllBytes()).strip());
|
||||
g.waitFor();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.ankurm.process;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* The classic ProcessBuilder hang: the child fills an OS pipe buffer (64 KiB on Linux) and blocks in
|
||||
* write(); the parent is waiting for the child to exit and never reads. Neither can proceed.
|
||||
*
|
||||
* <p>Every demo here has a deadline so the program always finishes.
|
||||
*/
|
||||
public final class DeadlockDemo {
|
||||
|
||||
/** Writes 200,000 bytes to the given stream: well past a 64 KiB pipe. */
|
||||
private static final String PRODUCE_STDOUT = "head -c 200000 /dev/zero | tr '\\0' x";
|
||||
private static final String PRODUCE_STDERR = "head -c 200000 /dev/zero | tr '\\0' e 1>&2";
|
||||
private static final String PRODUCE_BOTH = PRODUCE_STDOUT + "; " + PRODUCE_STDERR;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("== 1. WRONG: waitFor() first, read afterwards");
|
||||
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();
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. RIGHT (one stream): read to EOF, then waitFor()");
|
||||
Process q = new ProcessBuilder("sh", "-c", PRODUCE_STDOUT).start();
|
||||
byte[] all = q.getInputStream().readAllBytes();
|
||||
System.out.println("read " + all.length + " bytes, exit code " + q.waitFor());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. STILL WRONG: read stdout to EOF, but the child also fills stderr");
|
||||
Process r = new ProcessBuilder("sh", "-c", PRODUCE_BOTH).start();
|
||||
// Reading stdout to EOF blocks forever: the child is stuck writing stderr and never closes stdout.
|
||||
Thread reader = Thread.ofVirtual().start(() -> {
|
||||
try { r.getInputStream().readAllBytes(); } catch (Exception ignored) { }
|
||||
});
|
||||
reader.join(Duration.ofSeconds(3));
|
||||
System.out.println("stdout reader finished within 3s? " + !reader.isAlive());
|
||||
r.destroyForcibly().waitFor();
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. FIX A: merge stderr into stdout, one stream to drain");
|
||||
ProcessBuilder merged = new ProcessBuilder("sh", "-c", PRODUCE_BOTH).redirectErrorStream(true);
|
||||
Process s = merged.start();
|
||||
System.out.println("read " + s.getInputStream().readAllBytes().length + " bytes, exit code " + s.waitFor());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 5. FIX B: drain both streams concurrently (what ProcessRunner does)");
|
||||
ProcessRunner.Result res = ProcessRunner.run(List.of("sh", "-c", PRODUCE_BOTH));
|
||||
System.out.println("stdout=" + res.stdout().length() + " stderr=" + res.stderr().length()
|
||||
+ " exit=" + res.exitCode() + " timedOut=" + res.timedOut());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 6. FIX C: do not pipe at all. Send output to a file or discard it");
|
||||
Process t = new ProcessBuilder("sh", "-c", PRODUCE_BOTH)
|
||||
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
|
||||
.redirectError(ProcessBuilder.Redirect.DISCARD)
|
||||
.start();
|
||||
System.out.println("waitFor() returned immediately with exit code " + t.waitFor());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.ankurm.process;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** Environment variables, working directory and redirection: the configuration around start(). */
|
||||
public final class EnvironmentDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("== 1. the child inherits a COPY of our environment");
|
||||
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)");
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. clear() and rebuild: pass only what the child needs");
|
||||
ProcessBuilder clean = new ProcessBuilder("sh", "-c", "echo HOME=[$HOME] PATH=[$PATH] MODE=[$MODE]");
|
||||
clean.environment().clear();
|
||||
clean.environment().put("MODE", "minimal");
|
||||
System.out.println("child sees : " + run(clean));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. which PATH finds the program? start() uses OURS; the child's PATH is for the child");
|
||||
ProcessBuilder lookup = new ProcessBuilder("date", "+%Y");
|
||||
lookup.environment().put("PATH", "/nonexistent");
|
||||
System.out.println("start(\"date\") with child PATH=/nonexistent : " + run(lookup).matches("\\d{4}")
|
||||
+ " (resolved with the parent's PATH)");
|
||||
ProcessBuilder viaShell = new ProcessBuilder("sh", "-c", "date +%Y");
|
||||
viaShell.environment().put("PATH", "/nonexistent");
|
||||
System.out.println("sh -c 'date +%Y' with child PATH=/nonexistent : " + run(viaShell));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. working directory");
|
||||
Path dir = Files.createTempDirectory("procdemo");
|
||||
Files.writeString(dir.resolve("marker.txt"), "x");
|
||||
ProcessBuilder ls = new ProcessBuilder("ls").directory(dir.toFile());
|
||||
System.out.println("ls in temp dir: " + run(ls));
|
||||
try {
|
||||
new ProcessBuilder("ls").directory(new File("/no/such/dir")).start();
|
||||
} catch (Exception e) {
|
||||
System.out.println("bad directory -> " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||
}
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 5. redirect to files: no pipe, so nothing to drain");
|
||||
Path outFile = dir.resolve("out.log");
|
||||
Process p = new ProcessBuilder("sh", "-c", "echo to-stdout; echo to-stderr 1>&2")
|
||||
.redirectOutput(outFile.toFile())
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
System.out.println("exit " + p.waitFor() + ", file contains: "
|
||||
+ Files.readString(outFile).replace("\n", " | "));
|
||||
System.out.println("getInputStream() on a redirected process is a null stream: read() = "
|
||||
+ p.getInputStream().read());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 6. stdin: close it, or a reader like cat never sees EOF");
|
||||
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());
|
||||
}
|
||||
|
||||
private static String run(ProcessBuilder pb) throws Exception {
|
||||
pb.redirectErrorStream(true);
|
||||
Process p = pb.start();
|
||||
String s = new String(p.getInputStream().readAllBytes()).strip();
|
||||
p.waitFor();
|
||||
return s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ankurm.process;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/** ProcessHandle: pid, info, onExit(), pipelines, and looking at processes we did not start. */
|
||||
public final class HandleDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("== 1. our own process");
|
||||
ProcessHandle me = ProcessHandle.current();
|
||||
System.out.println("pid > 0: " + (me.pid() > 0) + ", command ends with java: "
|
||||
+ me.info().command().orElse("?").endsWith("java"));
|
||||
System.out.println("has a parent: " + me.parent().isPresent());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. onExit() instead of a blocked thread");
|
||||
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());
|
||||
done.join();
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. what ProcessHandle.Info reveals about a child");
|
||||
Process c = new ProcessBuilder("sleep", "5").start();
|
||||
ProcessHandle.Info info = c.info();
|
||||
System.out.println("command = " + info.command().orElse("?"));
|
||||
System.out.println("arguments = " + info.arguments().map(a -> String.join(" ", a)).orElse("?"));
|
||||
System.out.println("user set = " + info.user().isPresent() + ", startInstant set = "
|
||||
+ info.startInstant().isPresent());
|
||||
c.destroyForcibly().waitFor();
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. a handle to a finished process");
|
||||
System.out.println("alive after exit: " + c.toHandle().isAlive());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 5. a real pipeline without a shell: printf | sort | uniq -c");
|
||||
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();
|
||||
System.out.println("stages: " + procs.size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.ankurm.process;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/** Command injection through a shell string, option injection through an argument list, and the fixes. */
|
||||
public final class InjectionDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path dir = Files.createTempDirectory("inject");
|
||||
Files.writeString(dir.resolve("report.txt"), "quarterly numbers\n");
|
||||
Files.writeString(dir.resolve("secret.txt"), "TOP-SECRET\n");
|
||||
String hostile = "report.txt; cat secret.txt";
|
||||
|
||||
System.out.println("== 1. VULNERABLE: build a shell string from user input");
|
||||
run(dir, List.of("sh", "-c", "wc -c " + hostile));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. SAFE: argument list, no shell. The whole input is one filename");
|
||||
run(dir, List.of("wc", "-c", hostile));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. SAFE but still a trap: option injection. Input '-l' is read as a flag");
|
||||
run(dir, List.of("ls", "-l"));
|
||||
System.out.println("(the caller wanted to list a file called '-l'; ls took it as an option)");
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. FIX: '--' ends option parsing, then validate");
|
||||
run(dir, List.of("ls", "--", "-l"));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 5. FIX: allow-list the input before it gets anywhere near a command");
|
||||
for (String candidate : List.of("report.txt", hostile, "-l", "../etc/passwd")) {
|
||||
System.out.println(String.format("%-28s -> %s", "'" + candidate + "'", safeName(candidate)));
|
||||
}
|
||||
}
|
||||
|
||||
/** Conservative allow-list: a plain file name, no leading dash, no path separators. */
|
||||
static boolean safeName(String s) {
|
||||
return s.matches("[A-Za-z0-9][A-Za-z0-9._]{0,63}");
|
||||
}
|
||||
|
||||
private static void run(Path dir, List<String> cmd) throws Exception {
|
||||
ProcessBuilder pb = new ProcessBuilder(cmd).directory(dir.toFile()).redirectErrorStream(true);
|
||||
Process p = pb.start();
|
||||
String out = new String(p.getInputStream().readAllBytes()).strip().replace("\n", "\n ");
|
||||
System.out.println("$ " + String.join(" ", cmd.subList(0, Math.min(cmd.size(), 3))) + (cmd.size() > 3 ? " ..." : ""));
|
||||
System.out.println(" " + out + " [exit " + p.waitFor() + "]");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.ankurm.process;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* A small, safe "run a command and give me the result" helper.
|
||||
*
|
||||
* <p>What it does that a bare {@code new ProcessBuilder(...).start()} does not:
|
||||
* <ul>
|
||||
* <li>drains stdout and stderr <em>concurrently</em>, so no pipe can fill and block the child;</li>
|
||||
* <li>caps how much output it keeps (the child is still drained, so it never blocks);</li>
|
||||
* <li>closes stdin immediately, so a child that reads stdin sees EOF instead of hanging;</li>
|
||||
* <li>enforces a deadline and, on timeout, kills the whole process tree, not just the direct child;</li>
|
||||
* <li>never waits forever for the pipe readers: a grandchild that inherited the pipes cannot hold us hostage.</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class ProcessRunner {
|
||||
|
||||
/** Outcome of one run. {@code exitCode} is -1 when the process was killed on timeout. */
|
||||
public record Result(int exitCode, String stdout, String stderr,
|
||||
boolean timedOut, boolean truncated, Duration elapsed) {
|
||||
public boolean ok() { return !timedOut && exitCode == 0; }
|
||||
}
|
||||
|
||||
/** Immutable run settings. */
|
||||
public record Options(Duration timeout, long maxCaptureBytes, Map<String, String> extraEnv) {
|
||||
public static Options defaults() { return new Options(Duration.ofSeconds(10), 1 << 20, Map.of()); }
|
||||
public Options withTimeout(Duration d) { return new Options(d, maxCaptureBytes, extraEnv); }
|
||||
public Options withMaxCapture(long n) { return new Options(timeout, n, extraEnv); }
|
||||
}
|
||||
|
||||
/** How long to wait for the pipe readers to reach EOF after the child has exited. */
|
||||
static final Duration READER_GRACE = Duration.ofSeconds(1);
|
||||
|
||||
private ProcessRunner() { }
|
||||
|
||||
private static void joinUntil(Thread t, long deadlineNanos) throws InterruptedException {
|
||||
long left = deadlineNanos - System.nanoTime();
|
||||
if (left > 0) t.join(Duration.ofNanos(left));
|
||||
}
|
||||
|
||||
public static Result run(List<String> command) throws IOException, InterruptedException {
|
||||
return run(command, Options.defaults());
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
* Kills {@code p} and every descendant. Descendants must be snapshotted <em>before</em> the parent
|
||||
* dies: once it is gone its children are re-parented to init and {@code descendants()} no longer
|
||||
* finds them.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
private static void closeQuietly(InputStream in) {
|
||||
try { in.close(); } catch (IOException ignored) { }
|
||||
}
|
||||
|
||||
/** Reads a stream to EOF, keeping at most {@code max} bytes and discarding (not blocking on) the rest. */
|
||||
private static final class Capture implements Runnable {
|
||||
private final InputStream in;
|
||||
private final long max;
|
||||
private final ByteArrayOutputStream buf = new ByteArrayOutputStream();
|
||||
volatile boolean truncated;
|
||||
|
||||
Capture(InputStream in, long max) { this.in = in; this.max = max; }
|
||||
|
||||
@Override public void run() {
|
||||
byte[] chunk = new byte[8192];
|
||||
try {
|
||||
int n;
|
||||
while ((n = in.read(chunk)) != -1) {
|
||||
synchronized (buf) {
|
||||
long room = max - buf.size();
|
||||
if (room > 0) buf.write(chunk, 0, (int) Math.min(room, n));
|
||||
if (n > room) truncated = true;
|
||||
}
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
// stream closed by killTree/closeQuietly: stop reading
|
||||
}
|
||||
}
|
||||
|
||||
String text() {
|
||||
synchronized (buf) { return buf.toString(StandardCharsets.UTF_8); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.ankurm.process;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/** Timeouts, and why killing the direct child is not enough. */
|
||||
public final class TimeoutDemo {
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("== 1. waitFor(timeout) returns false; it does NOT stop the process");
|
||||
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)");
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 2. a shell command spawns a child; destroying the shell orphans it");
|
||||
Process sh = new ProcessBuilder("sh", "-c", "sleep 40 & wait").start();
|
||||
Thread.sleep(300);
|
||||
List<ProcessHandle> kids = sh.descendants().toList();
|
||||
System.out.println("descendants of the shell: " + kids.size() + " -> "
|
||||
+ kids.stream().map(h -> h.info().command().orElse("?")).toList());
|
||||
ProcessHandle orphan = kids.get(0);
|
||||
sh.destroyForcibly().waitFor();
|
||||
Thread.sleep(200);
|
||||
System.out.println("shell dead, orphan alive = " + orphan.isAlive() + " <- leaked process");
|
||||
orphan.destroyForcibly();
|
||||
orphan.onExit().join();
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 3. kill the tree: snapshot descendants first, then kill all");
|
||||
Process sh2 = new ProcessBuilder("sh", "-c", "sleep 40 & wait").start();
|
||||
Thread.sleep(300);
|
||||
ProcessHandle child = sh2.descendants().findFirst().orElseThrow();
|
||||
ProcessRunner.killTree(sh2);
|
||||
child.onExit().join();
|
||||
System.out.println("shell alive = " + sh2.isAlive() + ", former child alive = " + child.isAlive());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 4. ProcessRunner with a deadline");
|
||||
ProcessRunner.Result r = ProcessRunner.run(List.of("sh", "-c", "echo started; sleep 40 & wait"),
|
||||
ProcessRunner.Options.defaults().withTimeout(Duration.ofSeconds(1)));
|
||||
System.out.println("timedOut=" + r.timedOut() + " exit=" + r.exitCode() + " stdout=" + r.stdout().strip()
|
||||
+ " elapsed<2s=" + (r.elapsed().toMillis() < 2000));
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 5. a background grandchild keeps the pipe open: readAllBytes() waits for IT");
|
||||
long t0 = System.nanoTime();
|
||||
Process bg = new ProcessBuilder("sh", "-c", "(sleep 4; echo late) & echo done").start();
|
||||
byte[] out = bg.getInputStream().readAllBytes(); // blocks until the grandchild closes the pipe
|
||||
long ms = (System.nanoTime() - t0) / 1_000_000;
|
||||
System.out.println("sh exited at once, but readAllBytes() took ~" + (ms / 1000) + "s; got "
|
||||
+ new String(out).replace("\n", "|"));
|
||||
bg.waitFor();
|
||||
|
||||
System.out.println();
|
||||
System.out.println("== 6. ProcessRunner is not held hostage by the same command");
|
||||
ProcessRunner.Result r2 = ProcessRunner.run(List.of("sh", "-c", "(sleep 4; echo late) & echo done"),
|
||||
ProcessRunner.Options.defaults());
|
||||
System.out.println("exit=" + r2.exitCode() + " stdout=" + r2.stdout().replace("\n", "|")
|
||||
+ " returned in under 2s: " + (r2.elapsed().toMillis() < 2000)
|
||||
+ " (bounded by the 1s reader grace, not by the 4s grandchild)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.ankurm.process;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** One assertion per claim the post makes. Unix-only: it needs sh, sleep, head, tr, cat, wc. */
|
||||
class ProcessClaimsTest {
|
||||
|
||||
private static final String PRODUCE_STDOUT = "head -c 200000 /dev/zero | tr '\\0' x";
|
||||
private static final String PRODUCE_BOTH = PRODUCE_STDOUT + "; head -c 200000 /dev/zero | tr '\\0' e 1>&2";
|
||||
|
||||
@BeforeAll
|
||||
static void unixOnly() {
|
||||
assumeTrue(Files.isExecutable(Path.of("/bin/sh")), "needs a Unix shell");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failingCommandIsAnExitCodeAndMissingBinaryIsAnException() throws Exception {
|
||||
Process f = new ProcessBuilder("ls", "/definitely/not/here").start();
|
||||
f.getErrorStream().readAllBytes();
|
||||
assertEquals(2, f.waitFor());
|
||||
IOException e = assertThrows(IOException.class, () -> new ProcessBuilder("no-such-binary-xyz").start());
|
||||
assertTrue(e.getMessage().contains("error: 2") || e.getMessage().contains("error=2"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exitValueBeforeExitThrows() throws Exception {
|
||||
Process p = new ProcessBuilder("sleep", "5").start();
|
||||
try {
|
||||
assertThrows(IllegalThreadStateException.class, p::exitValue);
|
||||
assertFalse(p.waitFor(100, TimeUnit.MILLISECONDS));
|
||||
} finally {
|
||||
p.destroyForcibly().waitFor();
|
||||
}
|
||||
assertEquals(137, p.exitValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shellIsNotInvolved() throws Exception {
|
||||
Process g = new ProcessBuilder("echo", "*.txt", "$HOME", "a|b").start();
|
||||
assertEquals("*.txt $HOME a|b", new String(g.getInputStream().readAllBytes()).strip());
|
||||
g.waitFor();
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadPipeBlocksTheChildAtThePipeBufferSize() throws Exception {
|
||||
Process p = new ProcessBuilder("sh", "-c", PRODUCE_STDOUT).start();
|
||||
try {
|
||||
assertFalse(p.waitFor(2, TimeUnit.SECONDS), "child must be stuck in write()");
|
||||
assertTrue(p.isAlive());
|
||||
int inPipe = p.getInputStream().available();
|
||||
assertTrue(inPipe > 0 && inPipe < 200_000, "only a pipe-buffer's worth arrived: " + inPipe);
|
||||
} finally {
|
||||
p.destroyForcibly().waitFor();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void readingOnlyStdoutStillDeadlocksWhenStderrFills() throws Exception {
|
||||
Process r = new ProcessBuilder("sh", "-c", PRODUCE_BOTH).start();
|
||||
Thread reader = Thread.ofVirtual().start(() -> {
|
||||
try { r.getInputStream().readAllBytes(); } catch (Exception ignored) { }
|
||||
});
|
||||
try {
|
||||
reader.join(Duration.ofSeconds(2));
|
||||
assertTrue(reader.isAlive(), "stdout never reaches EOF while stderr is full");
|
||||
} finally {
|
||||
r.destroyForcibly().waitFor();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mergedStreamsAndConcurrentDrainBothFinish() throws Exception {
|
||||
Process s = new ProcessBuilder("sh", "-c", PRODUCE_BOTH).redirectErrorStream(true).start();
|
||||
assertEquals(400_000, s.getInputStream().readAllBytes().length);
|
||||
assertEquals(0, s.waitFor());
|
||||
|
||||
ProcessRunner.Result res = ProcessRunner.run(List.of("sh", "-c", PRODUCE_BOTH));
|
||||
assertEquals(200_000, res.stdout().length());
|
||||
assertEquals(200_000, res.stderr().length());
|
||||
assertTrue(res.ok());
|
||||
}
|
||||
|
||||
@Test
|
||||
void captureCapTruncatesButNeverBlocksTheChild() throws Exception {
|
||||
ProcessRunner.Result res = ProcessRunner.run(List.of("sh", "-c", PRODUCE_STDOUT),
|
||||
ProcessRunner.Options.defaults().withMaxCapture(1000));
|
||||
assertEquals(1000, res.stdout().length());
|
||||
assertTrue(res.truncated());
|
||||
assertEquals(0, res.exitCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void destroyingTheShellOrphansItsChildButKillTreeDoesNot() throws Exception {
|
||||
Process sh = new ProcessBuilder("sh", "-c", "sleep 40 & wait").start();
|
||||
Thread.sleep(300);
|
||||
ProcessHandle orphan = sh.descendants().findFirst().orElseThrow();
|
||||
sh.destroyForcibly().waitFor();
|
||||
Thread.sleep(200);
|
||||
assertEquals(0, sh.descendants().count(), "descendants() is empty once the parent is dead");
|
||||
assertTrue(orphan.isAlive(), "the orphan survives its parent");
|
||||
orphan.destroyForcibly();
|
||||
orphan.onExit().join();
|
||||
|
||||
Process sh2 = new ProcessBuilder("sh", "-c", "sleep 40 & wait").start();
|
||||
Thread.sleep(300);
|
||||
ProcessHandle child = sh2.descendants().findFirst().orElseThrow();
|
||||
ProcessRunner.killTree(sh2);
|
||||
child.onExit().join();
|
||||
assertFalse(child.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runnerTimeoutKillsTheWholeTree() throws Exception {
|
||||
ProcessRunner.Result r = ProcessRunner.run(List.of("sh", "-c", "sleep 40 & echo $!; wait"),
|
||||
ProcessRunner.Options.defaults().withTimeout(Duration.ofSeconds(1)));
|
||||
assertTrue(r.timedOut());
|
||||
assertEquals(-1, r.exitCode());
|
||||
long pid = Long.parseLong(r.stdout().strip());
|
||||
ProcessHandle gc = ProcessHandle.of(pid).orElse(null);
|
||||
if (gc != null) {
|
||||
gc.onExit().get(5, TimeUnit.SECONDS); // a killed non-child is noticed by polling, so allow a moment
|
||||
assertFalse(gc.isAlive(), "grandchild must be dead");
|
||||
}
|
||||
assertTrue(r.elapsed().toMillis() < 3000, "elapsed " + r.elapsed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBackgroundGrandchildHoldsAPlainReadHostageButNotTheRunner() throws Exception {
|
||||
// warm up: the very first spawn in a JVM is slow enough for the exit-time drain to hide the effect
|
||||
new ProcessBuilder("true").start().waitFor();
|
||||
long t0 = System.nanoTime();
|
||||
Process bg = new ProcessBuilder("sh", "-c", "(sleep 3; echo late) & echo done").start();
|
||||
byte[] out = bg.getInputStream().readAllBytes();
|
||||
long plainMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
bg.waitFor();
|
||||
assertTrue(plainMs >= 2500, "plain read waited for the grandchild: " + plainMs + " ms");
|
||||
assertEquals("done\nlate\n", new String(out));
|
||||
|
||||
ProcessRunner.Result r = ProcessRunner.run(List.of("sh", "-c", "(sleep 3; echo late) & echo done"));
|
||||
assertTrue(r.elapsed().toMillis() < 2000, "runner elapsed " + r.elapsed());
|
||||
assertEquals("done\n", r.stdout());
|
||||
}
|
||||
|
||||
@Test
|
||||
void environmentIsACopyAndProgramLookupUsesTheParentsPath() throws Exception {
|
||||
ProcessBuilder pb = new ProcessBuilder("sh", "-c", "echo $GREETING");
|
||||
pb.environment().put("GREETING", "hello");
|
||||
Process p = pb.start();
|
||||
assertEquals("hello", new String(p.getInputStream().readAllBytes()).strip());
|
||||
p.waitFor();
|
||||
assertNull(System.getenv("GREETING"));
|
||||
|
||||
ProcessBuilder viaShell = new ProcessBuilder("sh", "-c", "date +%Y").redirectErrorStream(true);
|
||||
viaShell.environment().put("PATH", "/nonexistent");
|
||||
Process q = viaShell.start();
|
||||
assertTrue(new String(q.getInputStream().readAllBytes()).contains("not found"));
|
||||
q.waitFor();
|
||||
|
||||
ProcessBuilder direct = new ProcessBuilder("date", "+%Y");
|
||||
direct.environment().put("PATH", "/nonexistent");
|
||||
Process d = direct.start();
|
||||
assertTrue(new String(d.getInputStream().readAllBytes()).strip().matches("\\d{4}"));
|
||||
d.waitFor();
|
||||
}
|
||||
|
||||
@Test
|
||||
void stdinMustBeClosedForCatToFinish() throws Exception {
|
||||
Process cat = new ProcessBuilder("cat").start();
|
||||
assertFalse(cat.waitFor(500, TimeUnit.MILLISECONDS), "cat waits for EOF on stdin");
|
||||
cat.getOutputStream().close();
|
||||
assertTrue(cat.waitFor(2, TimeUnit.SECONDS));
|
||||
|
||||
ProcessRunner.Result r = ProcessRunner.run(List.of("cat"));
|
||||
assertTrue(r.ok(), "the runner closes stdin up front");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shellStringInjectsButArgumentListDoesNot() throws Exception {
|
||||
Path dir = Files.createTempDirectory("inject");
|
||||
Files.writeString(dir.resolve("report.txt"), "quarterly numbers\n");
|
||||
Files.writeString(dir.resolve("secret.txt"), "TOP-SECRET\n");
|
||||
String hostile = "report.txt; cat secret.txt";
|
||||
|
||||
String shell = out(dir, List.of("sh", "-c", "wc -c " + hostile));
|
||||
assertTrue(shell.contains("TOP-SECRET"));
|
||||
String list = out(dir, List.of("wc", "-c", hostile));
|
||||
assertFalse(list.contains("TOP-SECRET"));
|
||||
|
||||
assertTrue(out(dir, List.of("ls", "-l")).contains("secret.txt"), "'-l' was taken as an option");
|
||||
assertTrue(out(dir, List.of("ls", "--", "-l")).contains("cannot access"));
|
||||
assertTrue(InjectionDemo.safeName("report.txt"));
|
||||
assertFalse(InjectionDemo.safeName(hostile));
|
||||
assertFalse(InjectionDemo.safeName("-l"));
|
||||
assertFalse(InjectionDemo.safeName("../etc/passwd"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pipelineWithoutAShell() throws Exception {
|
||||
List<Process> ps = ProcessBuilder.startPipeline(List.of(
|
||||
new ProcessBuilder("printf", "b\\na\\nb\\n"), new ProcessBuilder("sort"), new ProcessBuilder("uniq", "-c")));
|
||||
String out = new String(ps.get(2).getInputStream().readAllBytes());
|
||||
assertEquals(3, ps.size());
|
||||
assertEquals(" 1 a\n 2 b\n", out);
|
||||
}
|
||||
|
||||
private static String out(Path dir, List<String> cmd) throws Exception {
|
||||
Process p = new ProcessBuilder(cmd).directory(dir.toFile()).redirectErrorStream(true).start();
|
||||
String s = new String(p.getInputStream().readAllBytes());
|
||||
p.waitFor();
|
||||
return s;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user