Class Processes

java.lang.Object
org.kiwiproject.base.process.Processes

public final class Processes extends Object
Utility class for working with operating system processes.

Note that most of the methods are intended only for use on Unix/Linux operating systems.

See Also:
  • Field Details

  • Method Details

    • wasPgrepFlagsCheckSuccessful

      public static boolean wasPgrepFlagsCheckSuccessful()
      Use this method to determine if calling any of the pgrep methods in this class will work as expected.
      Returns:
      true if the pgrep check to determine the flags to use for full command matching was successful; false otherwise. If false you should NOT use any of the pgrep methods.
      See Also:
    • getPgrepFlags

      public static String getPgrepFlags()
      Returns the pgrep flags that Processes will use in all pgrep methods. Use wasPgrepFlagsCheckSuccessful() to check if the flags were chosen successfully to ensure that pgrep commands will work as expected on your OS.
      Returns:
      the flags that will be used in pgrep commands
    • processId

      public static long processId(Process process)
      Get a process id, or "pid".

      Earlier versions of Kiwi used to perform some nasty things (checking if the actual process class was java.lang.UNIXProcess, then using reflection to get the value of the private pid field) to obtain Process pids, but since JDK 9 offers the Process.pid() method, that is no longer necessary. This method is now a simple delegation to Process.pid() and you should now prefer that method.

      Parameters:
      process - the process to obtain the process id (pid) from
      Returns:
      the process id of process
      Throws:
      UnsupportedOperationException - if the Process implementation does not support getting the pid
      See Also:
    • processIdOrEmpty

      public static OptionalLong processIdOrEmpty(Process process)
      Get a process id, or "pid", if it is available from the Process implementation, wrapped inside an OptionalLong. If the pid is not available for whatever reason, return an empty OptionalLong.
      Parameters:
      process - the process to obtain the process id (pid) from
      Returns:
      an OptionalLong containing the process if of process or an empty OptionalLong if the Process implementation does not support getting the pid for whatever reason.
      Implementation Note:
      the Process.pid() method says it can throw UnsupportedOperationException if the "implementation does not support this operation" but does not specify under what circumstances that can happen, and I have not been able to find this information using Google, Bing, or DuckDuckGo. This method logs a warning along with the exception, so if this occurs check your logs for the possible reason.
    • hasSuccessfulExitCode

      public static boolean hasSuccessfulExitCode(Process process)
      Check if the given Process has an exit code representing successful termination.
      Parameters:
      process - the Process, assumed to have exited
      Returns:
      true if the process terminated successfully
      See Also:
    • isSuccessfulExitCode

      public static boolean isSuccessfulExitCode(int exitCode)
      Check if the given exit code represents successful termination.
      Parameters:
      exitCode - the exit code to check
      Returns:
      true if the exit code represents success
      See Also:
    • isNonzeroExitCode

      public static boolean isNonzeroExitCode(int exitCode)
      Check if the given exit code represents anything other than successful termination. In other words, is the exit code nonzero?
      Parameters:
      exitCode - the exit code to check
      Returns:
      true if the exit code is nonzero
      See Also:
      Implementation Note:
      This method is specifically named to indicate that the exit code does not represent success, leaving the possibility open that a nonzero exit code can indicate some condition other than an error.
    • waitForExit

      public static Optional<Integer> waitForExit(Process process)
      Waits up to DEFAULT_WAIT_FOR_EXIT_TIME_SECONDS for the given process to exit.

      Note that this method does not destroy the process if it times out waiting.

      Parameters:
      process - the process to wait for
      Returns:
      an Optional that will contain the exit code if the process exited before the timeout, or empty if the process did not exit before the timeout expired.
    • waitForExit

      public static Optional<Integer> waitForExit(Process process, long timeout, TimeUnit unit)
      Waits up to the specified timeout for the given process to exit.

      Note that this method does not destroy the process if it times out waiting.

      Parameters:
      process - the process to wait for
      timeout - the value of the time to wait
      unit - the unit of time to wait
      Returns:
      an Optional that will contain the exit code if the process exited before the timeout, or empty if the process did not exit before the timeout expired.
    • launch

      public static Process launch(List<String> command)
      Launches a new process using the specified command. This is just a convenience wrapper around creating a new ProcessBuilder and calling ProcessBuilder.start().

      This wrapper also converts any thrown IOException to an UncheckedIOException.

      If you need more flexibility than provided in this simple wrapper, use ProcessBuilder directly.

      Parameters:
      command - the list containing the program and its arguments
      Returns:
      the new Process
      See Also:
    • launch

      public static Process launch(@Nullable File workingDirectory, List<String> command)
      Launches a new process using the specified command with the given working directory. This is just a convenience wrapper around creating a new ProcessBuilder, setting the working directory, and calling ProcessBuilder.start().

      This wrapper converts any thrown IOException to an UncheckedIOException.

      If you need more flexibility than provided in this simple wrapper, use ProcessBuilder directly.

      Parameters:
      workingDirectory - the working directory to use
      command - the list containing the program and its arguments
      Returns:
      the new Process
      See Also:
    • launch

      public static Process launch(String... command)
      Launches a new process using the specified command.
      Parameters:
      command - a list containing the program and its arguments
      Returns:
      the new Process
      See Also:
    • pgrep

      public static List<Long> pgrep(String commandLine)
      Does a pgrep with the specified full command.
      Parameters:
      commandLine - the full command to match
      Returns:
      a list of matching process ids (pids)
      See Also:
    • pgrep

      public static List<Long> pgrep(String user, String commandLine)
      Does a pgrep with the specified full command.
      Parameters:
      user - the OS user (passed to the -u option)
      commandLine - the full command to match
      Returns:
      list of matching process ids (pids)
      See Also:
    • pgrepWithSingleResult

      public static Optional<Long> pgrepWithSingleResult(String commandLine)
      Does a pgrep against the specified full command, expecting a single result, or no result.
      Parameters:
      commandLine - the full command line
      Returns:
      an optional either containing a process id, or an empty optional
      See Also:
    • pgrepWithSingleResult

      public static Optional<Long> pgrepWithSingleResult(String user, String commandLine)
      Does a pgrep against the specified full command, expecting a single result for a specific user, or no result.
      Parameters:
      user - the OS user (passed to the -u option)
      commandLine - the full command to match
      Returns:
      an optional either containing a process id, or an empty optional
      See Also:
    • pgrepList

      public static List<String> pgrepList(String commandLine)
      Does a pgrep with the specified full command.
      Parameters:
      commandLine - the full command line to match
      Returns:
      a list of pgrep output, with each line in format "{pid} {command}"
      See Also:
    • pgrepList

      public static List<String> pgrepList(String user, String commandLine)
      Does a pgrep with the specified full command.
      Parameters:
      user - the OS user (passed to the -u option)
      commandLine - the full command line to match
      Returns:
      a list of pgrep output, with each line in format "{pid} {command}"
      See Also:
    • pgrepParsedList

      public static List<org.apache.commons.lang3.tuple.Pair<Long,String>> pgrepParsedList(String commandLine)
      Does a pgrep for the specified full command, returning a list of pairs containing the process id (pid) and the matched command line.
      Parameters:
      commandLine - the full command line to match
      Returns:
      a list of Pair objects; each pair contains the pid as a Long and the associated full command
      See Also:
    • pgrepParsedList

      public static List<org.apache.commons.lang3.tuple.Pair<Long,String>> pgrepParsedList(String user, String commandLine)
      Does a pgrep for the specified full command, returning a list of pairs containing the process id (pid) and the matched command line.
      Parameters:
      user - the OS user (passed to the -u option)
      commandLine - the full command line to match
      Returns:
      a list of Pair objects; each pair contains the pid as a Long and the associated full command
      See Also:
    • kill

      public static int kill(long processId, KillSignal signal, KillTimeoutAction action)
      Kill a process, waiting up to DEFAULT_KILL_TIMEOUT_SECONDS seconds for it to terminate.
      Parameters:
      processId - the pid of the process to kill
      signal - the kill signal; this could be the signal number (e.g. "1") or name (e.g. "SIGHUP")
      action - the KillTimeoutAction to take if the process doesn't terminate within the allotted time
      Returns:
      the exit code from the kill command, or -1 if action is
      See Also:
    • kill

      public static int kill(long processId, String signal, KillTimeoutAction action)
      Kill a process, waiting up to DEFAULT_KILL_TIMEOUT_SECONDS seconds for it to terminate.
      Parameters:
      processId - the pid of the process to kill
      signal - the kill signal; this could be the signal number (e.g. "1") or name (e.g. "SIGHUP")
      action - the KillTimeoutAction to take if the process doesn't terminate within the allotted time
      Returns:
      the exit code from the kill command, or -1 if action is KillTimeoutAction.NO_OP and the kill command times out
      Throws:
      UncheckedIOException - if an I/O error occurs killing the process
    • kill

      public static int kill(long processId, KillSignal signal, long timeout, TimeUnit unit, KillTimeoutAction action)
      Kill a process, waiting up to timeout in the specified TimeUnit for it to terminate.
      Parameters:
      processId - the pid of the process to kill
      signal - the kill signal enum
      timeout - the time to wait for the process to be killed
      unit - the time unit associated with timeout
      action - the KillTimeoutAction to take if the process doesn't terminate within the allotted time
      Returns:
      the exit code from the kill command, or -1 if action is
      See Also:
    • kill

      public static int kill(long processId, String signal, long timeout, TimeUnit unit, KillTimeoutAction action)
      Kill a process, waiting up to timeout in the specified TimeUnit for it to terminate.
      Parameters:
      processId - the pid of the process to kill
      signal - the kill signal; this could be the signal number (e.g. "1") or name (e.g. "SIGHUP")
      timeout - the time to wait for the process to be killed
      unit - the time unit associated with timeout
      action - the KillTimeoutAction to take if the process doesn't terminate within the allotted time
      Returns:
      the exit code from the kill command, or -1 if action is KillTimeoutAction.NO_OP and the kill command times out
      Throws:
      UncheckedIOException - if an I/O error occurs killing the process
    • killForcibly

      public static boolean killForcibly(Process process, long timeout, TimeUnit unit) throws InterruptedException
      Equivalent to a kill -9 (i.e. a SIGKILL).
      Parameters:
      process - the process to kill forcibly
      timeout - the time to wait for the process to be forcibly killed
      unit - the time unit associated with the timeout
      Returns:
      true if process was killed before the timeout period elapsed; false otherwise
      Throws:
      InterruptedException - if the current thread is interrupted while waiting
      See Also:
    • whichAsPath

      public static Optional<Path> whichAsPath(String program)
      Locate a program in the user's path, returning the result as a Path.
      Parameters:
      program - the program to locate
      Returns:
      an Optional containing the full Path to the program, or an empty Optional if not found
      Implementation Note:
      If there is more than program found, only the first one is returned
    • which

      public static Optional<String> which(String program)
      Locate a program in the user's path.
      Parameters:
      program - the program to locate
      Returns:
      an Optional containing the full path to the program, or an empty Optional if not found
      Implementation Note:
      If there is more than program found, only the first one is returned