Package org.kiwiproject.base.process
Class Processes
- java.lang.Object
-
- org.kiwiproject.base.process.Processes
-
public 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:
ProcessHelper
-
-
Field Summary
Fields Modifier and Type Field Description static intDEFAULT_KILL_TIMEOUT_SECONDSDefault number of seconds to wait for termination of a process.static longDEFAULT_WAIT_FOR_EXIT_TIME_SECONDSDefault number of seconds to wait for a process to exit.static intSUCCESS_EXIT_CODEExit code that indicates aProcessterminated normally.
-
Constructor Summary
Constructors Constructor Description Processes()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static StringgetPgrepFlags()Returns the pgrep flags thatProcesseswill use in all pgrep methods.static booleanhasSuccessfulExitCode(Process process)Check if the givenProcesshas an exit code representing successful termination.static booleanisSuccessfulExitCode(int exitCode)Check if the given exit code represents successful termination.static intkill(long processId, String signal, long timeout, TimeUnit unit, KillTimeoutAction action)Kill a process, waiting up totimeoutin the specifiedTimeUnitfor it to terminate.static intkill(long processId, String signal, KillTimeoutAction action)Kill a process, waiting up toDEFAULT_KILL_TIMEOUT_SECONDSseconds for it to terminate.static intkill(long processId, KillSignal signal, long timeout, TimeUnit unit, KillTimeoutAction action)Kill a process, waiting up totimeoutin the specifiedTimeUnitfor it to terminate.static intkill(long processId, KillSignal signal, KillTimeoutAction action)Kill a process, waiting up toDEFAULT_KILL_TIMEOUT_SECONDSseconds for it to terminate.static booleankillForcibly(Process process, long timeout, TimeUnit unit)Equivalent to akill -9(i.e.static Processlaunch(String... command)Launches a new process using the specifiedcommand.static Processlaunch(List<String> command)Launches a new process using the specifiedcommand.static List<Long>pgrep(String commandLine)Does apgrepwith the specified full command.static List<Long>pgrep(String user, String commandLine)Does apgrepwith the specified full command.static List<String>pgrepList(String commandLine)Does apgrepwith the specified full command.static List<String>pgrepList(String user, String commandLine)Does apgrepwith the specified full command.static List<org.apache.commons.lang3.tuple.Pair<Long,String>>pgrepParsedList(String commandLine)Does apgrepfor the specified full command, returning a list of pairs containing the process id (pid) and the matched command line.static List<org.apache.commons.lang3.tuple.Pair<Long,String>>pgrepParsedList(String user, String commandLine)Does apgrepfor the specified full command, returning a list of pairs containing the process id (pid) and the matched command line.static Optional<Long>pgrepWithSingleResult(String commandLine)Does apgrepagainst the specified full command, expecting a single result, or no result.static Optional<Long>pgrepWithSingleResult(String user, String commandLine)Does apgrepagainst the specified full command, expecting a single result for a specific user, or no result.static longprocessId(Process process)Get a process id, or "pid".static OptionalLongprocessIdOrEmpty(Process process)Get a process id, or "pid", if it is available from theProcessimplementation, wrapped inside an OptionalLong.static Optional<Integer>waitForExit(Process process)Waits up toDEFAULT_WAIT_FOR_EXIT_TIME_SECONDSfor the given process to exit.static Optional<Integer>waitForExit(Process process, long timeout, TimeUnit unit)Waits up to the specifiedtimeoutfor the given process to exit.static booleanwasPgrepFlagsCheckSuccessful()Use this method to determine if calling any of the pgrep methods in this class will work as expected.
-
-
-
Field Detail
-
SUCCESS_EXIT_CODE
public static final int SUCCESS_EXIT_CODE
Exit code that indicates aProcessterminated normally.- See Also:
Process.exitValue(), Constant Field Values
-
DEFAULT_KILL_TIMEOUT_SECONDS
public static final int DEFAULT_KILL_TIMEOUT_SECONDS
Default number of seconds to wait for termination of a process.
-
DEFAULT_WAIT_FOR_EXIT_TIME_SECONDS
public static final long DEFAULT_WAIT_FOR_EXIT_TIME_SECONDS
Default number of seconds to wait for a process to exit.- See Also:
waitForExit(Process), Constant Field Values
-
-
Method Detail
-
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()
-
getPgrepFlags
public static String getPgrepFlags()
Returns the pgrep flags thatProcesseswill use in all pgrep methods. UsewasPgrepFlagsCheckSuccessful()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 privatepidfield) to obtain Process pids, but since JDK 9 offers theProcess.pid()method, that is no longer necessary. This method is now a simple delegation toProcess.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:
Process.pid()
-
processIdOrEmpty
public static OptionalLong processIdOrEmpty(Process process)
Get a process id, or "pid", if it is available from theProcessimplementation, 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
processor an empty OptionalLong if theProcessimplementation does not support getting the pid for whatever reason. - Implementation Note:
- the
Process.pid()method says it can throwUnsupportedOperationExceptionif 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 givenProcesshas an exit code representing successful termination.- Parameters:
process- the Process, assumed to have exited- Returns:
- true if the process terminated successfully
- See Also:
isSuccessfulExitCode(int),SUCCESS_EXIT_CODE,Process.exitValue()
-
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:
SUCCESS_EXIT_CODE,Process.exitValue()
-
waitForExit
public static Optional<Integer> waitForExit(Process process)
Waits up toDEFAULT_WAIT_FOR_EXIT_TIME_SECONDSfor the given process to exit.- Parameters:
process- the process to wait for- Returns:
- an
Optionalthat 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 specifiedtimeoutfor the given process to exit.- Parameters:
process- the process to wait fortimeout- the value of the time to waitunit- the unit of time to wait- Returns:
- an
Optionalthat 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 specifiedcommand. This is just a convenience wrapper around creating a newProcessBuilderand callingProcessBuilder.start().This wrapper also converts any thrown
IOExceptionto anUncheckedIOException.If you need more flexibility than provided in this simple wrapper, use
ProcessBuilderdirectly.- Parameters:
command- the list containing the program and its arguments- Returns:
- the new
Process - See Also:
ProcessBuilder(List),ProcessBuilder.start()
-
launch
public static Process launch(String... command)
Launches a new process using the specifiedcommand.- Parameters:
command- a list containing the program and its arguments- Returns:
- the new
Process - See Also:
launch(List)
-
pgrep
public static List<Long> pgrep(String commandLine)
Does apgrepwith the specified full command.- Parameters:
commandLine- the full command to match- Returns:
- a list of matching process ids (pids)
- See Also:
pgrep(String, String),wasPgrepFlagsCheckSuccessful(),getPgrepFlags()
-
pgrep
public static List<Long> pgrep(String user, String commandLine)
Does apgrepwith the specified full command.- Parameters:
user- the OS user (passed to the-uoption)commandLine- the full command to match- Returns:
- list of matching process ids (pids)
- See Also:
wasPgrepFlagsCheckSuccessful(),getPgrepFlags()
-
pgrepWithSingleResult
public static Optional<Long> pgrepWithSingleResult(String commandLine)
Does apgrepagainst 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:
wasPgrepFlagsCheckSuccessful(),getPgrepFlags()
-
pgrepWithSingleResult
public static Optional<Long> pgrepWithSingleResult(String user, String commandLine)
Does apgrepagainst the specified full command, expecting a single result for a specific user, or no result.- Parameters:
user- the OS user (passed to the-uoption)commandLine- the full command to match- Returns:
- an optional either containing a process id, or an empty optional
- See Also:
wasPgrepFlagsCheckSuccessful(),getPgrepFlags()
-
pgrepList
public static List<String> pgrepList(String commandLine)
Does apgrepwith 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(String, String),wasPgrepFlagsCheckSuccessful(),getPgrepFlags()
-
pgrepList
public static List<String> pgrepList(String user, String commandLine)
Does apgrepwith the specified full command.- Parameters:
user- the OS user (passed to the-uoption)commandLine- the full command line to match- Returns:
- a list of pgrep output, with each line in format "{pid} {command}"
- See Also:
wasPgrepFlagsCheckSuccessful(),getPgrepFlags()
-
pgrepParsedList
public static List<org.apache.commons.lang3.tuple.Pair<Long,String>> pgrepParsedList(String commandLine)
Does apgrepfor 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
Pairobjects; each pair contains the pid as a Long and the associated full command - See Also:
pgrepParsedList(String, String),wasPgrepFlagsCheckSuccessful(),getPgrepFlags()
-
pgrepParsedList
public static List<org.apache.commons.lang3.tuple.Pair<Long,String>> pgrepParsedList(String user, String commandLine)
Does apgrepfor 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-uoption)commandLine- the full command line to match- Returns:
- a list of
Pairobjects; each pair contains the pid as a Long and the associated full command - See Also:
wasPgrepFlagsCheckSuccessful(),getPgrepFlags()
-
kill
public static int kill(long processId, KillSignal signal, KillTimeoutAction action)Kill a process, waiting up toDEFAULT_KILL_TIMEOUT_SECONDSseconds for it to terminate.- Parameters:
processId- the pid of the process to killsignal- the kill signal; this could be the signal number (e.g. "1") or name (e.g. "SIGHUP")action- theKillTimeoutActionto take if the process doesn't terminate within the allotted time- Returns:
- the exit code from the
killcommand, or-1ifactionis - See Also:
kill(long, String, long, TimeUnit, KillTimeoutAction)
-
kill
public static int kill(long processId, String signal, KillTimeoutAction action)Kill a process, waiting up toDEFAULT_KILL_TIMEOUT_SECONDSseconds for it to terminate.- Parameters:
processId- the pid of the process to killsignal- the kill signal; this could be the signal number (e.g. "1") or name (e.g. "SIGHUP")action- theKillTimeoutActionto take if the process doesn't terminate within the allotted time- Returns:
- the exit code from the
killcommand, or-1ifactionisKillTimeoutAction.NO_OPand 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 totimeoutin the specifiedTimeUnitfor it to terminate.- Parameters:
processId- the pid of the process to killsignal- the kill signal enumtimeout- the time to wait for the process to be killedunit- the time unit associated withtimeoutaction- theKillTimeoutActionto take if the process doesn't terminate within the allotted time- Returns:
- the exit code from the
killcommand, or-1ifactionis - See Also:
kill(long, String, long, TimeUnit, KillTimeoutAction)
-
kill
public static int kill(long processId, String signal, long timeout, TimeUnit unit, KillTimeoutAction action)Kill a process, waiting up totimeoutin the specifiedTimeUnitfor it to terminate.- Parameters:
processId- the pid of the process to killsignal- 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 killedunit- the time unit associated withtimeoutaction- theKillTimeoutActionto take if the process doesn't terminate within the allotted time- Returns:
- the exit code from the
killcommand, or-1ifactionisKillTimeoutAction.NO_OPand 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 akill -9(i.e. aSIGKILL).- Parameters:
process- the process to kill forciblytimeout- the time to wait for the process to be forcibly killedunit- the time unit associated with thetimeout- Returns:
trueifprocesswas killed before the timeout period elapsed;falseotherwise- Throws:
InterruptedException- if the current thread is interrupted while waiting- See Also:
Process.destroyForcibly(),Process.waitFor(long, TimeUnit)
-
-