Class ProcessManager

java.lang.Object
cloud.opencode.base.core.process.ProcessManager

public final class ProcessManager extends Object
ProcessManager - Process management utility facade ProcessManager - 进程管理工具门面

Provides a comprehensive set of static methods for process discovery, execution, and control using the JDK ProcessHandle and ProcessBuilder APIs.

使用 JDK ProcessHandleProcessBuilder API 提供一整套进程发现、 执行和控制的静态方法。

Features | 主要功能:

  • Process discovery: list, find by PID, name, or command - 进程发现:列表、按 PID/名称/命令查找
  • Process tree: children and descendants - 进程树:子进程和后代进程
  • Process execution: run commands with timeout, capture output - 进程执行:运行命令、超时、捕获输出
  • Process control: kill, force kill, wait, alive check - 进程控制:终止、强制终止、等待、存活检查

Usage Examples | 使用示例:

// Execute a command and capture output
ProcessResult result = ProcessManager.execute("ls", "-la");
System.out.println(result.stdout());

// Find processes by name
List<ProcessInfo> javaProcesses = ProcessManager.findByName("java");

// Execute with configuration
ProcessConfig config = ProcessConfig.builder("git", "status")
        .workingDirectory(Path.of("/my/repo"))
        .timeout(Duration.ofSeconds(10))
        .build();
ProcessResult gitResult = ProcessManager.execute(config);

Thread Safety | 线程安全: All methods are stateless and thread-safe. 所有方法都是无状态的,线程安全。

Output Capture Limit | 输出捕获限制: stdout and stderr are each limited to 10 MB to prevent out-of-memory errors. Excess output is truncated.

stdout 和 stderr 各限制为 10 MB 以防止内存溢出。超出部分将被截断。

Since:
JDK 25, opencode-base-core V1.0.3
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • current

      public static ProcessInfo current()
      Returns information about the current JVM process. 返回当前 JVM 进程的信息。
      Returns:
      process info for the current process - 当前进程的进程信息
    • find

      public static Optional<ProcessInfo> find(long pid)
      Finds a process by its PID. 通过 PID 查找进程。
      Parameters:
      pid - the process ID to find - 要查找的进程 ID
      Returns:
      an Optional containing the process info, or empty if not found - 包含进程信息的 Optional,未找到时为空
    • listAll

      public static List<ProcessInfo> listAll()
      Lists all visible processes on the system. 列出系统上所有可见的进程。

      Note: The returned list is a snapshot and may not reflect real-time state. Visibility depends on OS permissions. This method scans all OS processes and may be expensive on systems with many active processes — avoid calling in tight loops.

      注意:返回的列表是快照,可能不反映实时状态。可见性取决于操作系统权限。 此方法扫描所有系统进程,在进程数量多的系统上开销较大——避免在紧密循环中调用。

      Security Warning | 安全警告: Process command lines may contain sensitive credentials passed as arguments. Do not log or expose the returned list to untrusted parties.

      安全警告: 进程命令行可能包含作为参数传递的敏感凭据。 切勿将返回的列表记录日志或暴露给不可信方。

      Returns:
      list of all visible processes - 所有可见进程的列表
    • findByName

      public static List<ProcessInfo> findByName(String name)
      Finds processes whose command name contains the given string (case-insensitive). 查找命令名称包含给定字符串的进程(不区分大小写)。
      Parameters:
      name - the name to search for (contains match) - 要搜索的名称(包含匹配)
      Returns:
      list of matching processes - 匹配进程的列表
      Throws:
      NullPointerException - if name is null - 若 name 为 null
    • findByCommand

      public static List<ProcessInfo> findByCommand(String command)
      Finds processes whose full command line contains the given string (case-insensitive). 查找完整命令行包含给定字符串的进程(不区分大小写)。
      Parameters:
      command - the command string to search for (contains match) - 要搜索的命令字符串(包含匹配)
      Returns:
      list of matching processes - 匹配进程的列表
      Throws:
      NullPointerException - if command is null - 若 command 为 null
    • currentPid

      public static long currentPid()
      Returns the PID of the current JVM process. 返回当前 JVM 进程的 PID。
      Returns:
      the current process PID - 当前进程 PID
    • parent

      public static Optional<ProcessInfo> parent()
      Returns information about the parent process of the current JVM. 返回当前 JVM 父进程的信息。
      Returns:
      an Optional containing parent process info, or empty if no parent - 包含父进程信息的 Optional,无父进程时为空
    • children

      public static List<ProcessInfo> children()
      Returns direct children of the current JVM process. 返回当前 JVM 进程的直接子进程。
      Returns:
      list of direct child processes - 直接子进程列表
    • children

      public static List<ProcessInfo> children(long pid)
      Returns direct children of the process with the given PID. 返回给定 PID 进程的直接子进程。
      Parameters:
      pid - the parent process PID - 父进程 PID
      Returns:
      list of direct child processes, or empty if PID not found - 直接子进程列表,若 PID 未找到则为空
    • descendants

      public static List<ProcessInfo> descendants()
      Returns all descendants of the current JVM process. 返回当前 JVM 进程的所有后代进程。
      Returns:
      list of all descendant processes - 所有后代进程列表
    • descendants

      public static List<ProcessInfo> descendants(long pid)
      Returns all descendants of the process with the given PID. 返回给定 PID 进程的所有后代进程。
      Parameters:
      pid - the ancestor process PID - 祖先进程 PID
      Returns:
      list of all descendant processes, or empty if PID not found - 所有后代进程列表,若 PID 未找到则为空
    • execute

      public static ProcessResult execute(String... command)
      Executes a command and waits for completion, capturing stdout and stderr. 执行命令并等待完成,捕获 stdout 和 stderr。

      Security Warning | 安全警告: Never pass untrusted user input directly as command arguments. Validate and sanitize all inputs before execution. Avoid invoking shell interpreters (sh -c, cmd /c) with concatenated arguments.

      安全警告: 切勿将不可信的用户输入直接作为命令参数传入。 执行前请验证和清理所有输入。避免使用 shell 解释器拼接参数。

      Parameters:
      command - the command and arguments - 命令和参数
      Returns:
      the execution result - 执行结果
      Throws:
      OpenException - if the process cannot be started or is interrupted - 若进程无法启动或被中断
    • execute

      public static ProcessResult execute(List<String> command)
      Executes a command and waits for completion, capturing stdout and stderr. 执行命令并等待完成,捕获 stdout 和 stderr。
      Parameters:
      command - the command and arguments - 命令和参数
      Returns:
      the execution result - 执行结果
      Throws:
      OpenException - if the process cannot be started or is interrupted - 若进程无法启动或被中断
    • execute

      public static ProcessResult execute(ProcessConfig config)
      Executes a command with the given configuration and waits for completion. 使用给定配置执行命令并等待完成。

      stdout and stderr are captured in parallel threads to avoid deadlock when the process output exceeds the OS pipe buffer size. Each stream is limited to 10485760 bytes.

      stdout 和 stderr 在并行线程中捕获,以避免当进程输出超过操作系统管道缓冲区大小时的死锁。 每个流限制为 10485760 字节。

      Parameters:
      config - the process configuration - 进程配置
      Returns:
      the execution result - 执行结果
      Throws:
      OpenException - if the process cannot be started, times out, or is interrupted - 若进程无法启动、超时或被中断
    • start

      public static Process start(String... command)
      Starts a process without waiting for completion. 启动进程但不等待完成。

      Security Warning | 安全警告: Never pass untrusted user input directly as command arguments. See execute(String...) for details.

      安全警告: 切勿将不可信的用户输入直接作为命令参数传入。

      Parameters:
      command - the command and arguments - 命令和参数
      Returns:
      the started Process - 启动的进程
      Throws:
      OpenException - if the process cannot be started - 若进程无法启动
    • start

      public static Process start(ProcessConfig config)
      Starts a process with the given configuration without waiting for completion. 使用给定配置启动进程但不等待完成。
      Parameters:
      config - the process configuration - 进程配置
      Returns:
      the started Process - 启动的进程
      Throws:
      OpenException - if the process cannot be started - 若进程无法启动
    • kill

      public static boolean kill(long pid)
      Sends a normal termination request to the process with the given PID. 向给定 PID 的进程发送正常终止请求。
      Parameters:
      pid - the process ID - 进程 ID
      Returns:
      true if the process was found and the request was sent - 若进程被找到且请求已发送则为 true
    • killForcibly

      public static boolean killForcibly(long pid)
      Forcibly terminates the process with the given PID. 强制终止给定 PID 的进程。
      Parameters:
      pid - the process ID - 进程 ID
      Returns:
      true if the process was found and forcibly terminated - 若进程被找到且已被强制终止则为 true
    • isAlive

      public static boolean isAlive(long pid)
      Checks whether the process with the given PID is alive. 检查给定 PID 的进程是否存活。
      Parameters:
      pid - the process ID - 进程 ID
      Returns:
      true if the process exists and is alive - 若进程存在且存活则为 true
    • waitFor

      public static Optional<Integer> waitFor(long pid, long timeout, TimeUnit unit)
      Waits for the process with the given PID to exit, with a timeout. 等待给定 PID 的进程退出,带超时。
      Parameters:
      pid - the process ID - 进程 ID
      timeout - the maximum time to wait - 最大等待时间
      unit - the time unit - 时间单位
      Returns:
      an Optional containing the exit status, or empty if the process was not found or did not exit within the timeout - 包含退出状态的 Optional,若进程未找到或未在超时内退出则为空
      Throws:
      NullPointerException - if unit is null - 若 unit 为 null