Video in progress

You launched an external command with `ProcessBuilder` and `waitFor()` never returns. What happened from an IO standpoint?

The child process writes to stdout or stderr and you don't read it. Once the OS pipe buffer (usually 64 KB on Linux) fills up, the process blocks in write and never finishes, while you wait for it to finish. You need to read the streams, redirect them to a file, or discard them.

📖 Answer

Process p = new ProcessBuilder("ffmpeg", "-i", in, out).start();
int code = p.waitFor();     // ffmpeg writes a lot to stderr -> waits forever

It works on a small test file, because the output doesn't reach 64 KB. On prod, with a big file, it hangs for a day, and in a thread dump the thread is in waitFor while the process is alive in ps.

The options:

// 1) if you don't need the output
pb.redirectOutput(ProcessBuilder.Redirect.DISCARD)    // Java 9+
  .redirectError(ProcessBuilder.Redirect.DISCARD);

// 2) to a file for logging
pb.redirectErrorStream(true)
  .redirectOutput(ProcessBuilder.Redirect.appendTo(logFile.toFile()));

// 3) read the output in code: merge stderr into stdout and read a single stream
pb.redirectErrorStream(true);
Process p = pb.start();
try (BufferedReader r = p.inputReader(StandardCharsets.UTF_8)) {   // Java 17+
    r.lines().forEach(log::info);
}

If you need both streams separately, you read them in two different threads: reading one to the end and then moving on to the other gives a deadlock again.

A few more rules:

  • waitFor(timeout, unit), and destroy() once the time is up, then destroyForcibly(). Don't wait indefinitely on an external command;
  • if the process is waiting for input on stdin, do p.getOutputStream().close() or give it redirectInput(Redirect.from(...));
  • which encoding the output uses depends on the child process; pass it explicitly with inputReader(Charset);
  • don't join the arguments into one string and pass it to sh -c; pass them as a list: that protects you from shell injection.