001package net.bramp.ffmpeg.io;
002
003import java.util.concurrent.TimeUnit;
004import java.util.concurrent.TimeoutException;
005
006/**
007 * A collection of utility methods for dealing with processes.
008 *
009 * @author bramp
010 */
011public final class ProcessUtils {
012  private ProcessUtils() {
013    throw new AssertionError("No instances for you!");
014  }
015
016  /**
017   * Waits until a process finishes or a timeout occurs.
018   *
019   * @param p process
020   * @param timeout timeout in given unit
021   * @param unit time unit
022   * @return the process exit value
023   * @throws TimeoutException if a timeout occurs
024   */
025  public static int waitForWithTimeout(final Process p, long timeout, TimeUnit unit)
026      throws TimeoutException {
027
028    try {
029      p.waitFor(timeout, unit);
030
031    } catch (InterruptedException e) {
032      Thread.currentThread().interrupt();
033    }
034
035    if (p.isAlive()) {
036      throw new TimeoutException("Process did not finish within timeout");
037    }
038
039    return p.exitValue();
040  }
041}