仓颉标准库 process 包详解:进程创建、信息查询与子进程管理实战

原创2026-10-14 11:48:491,885 阅读
文章标签:文档知识库

仓颉标准库 process 包详解:进程创建、信息查询与子进程管理实战

导读

std.process 是仓颉编程语言标准库中负责进程操作的核心包,围绕 Process、CurrentProcess、SubProcess 三个类提供进程创建、标准流获取、进程等待、进程信息查询与进程终止等能力,并依托 ProcessRedirect 枚举实现标准流重定向。本文以 process 包类文档 为主体,结合 process 包概览、顶层函数文档、ProcessRedirect 枚举文档 及仓库内置示例,完整讲解每个类与成员的签名、语义、平台差异与异常行为,并给出可直接运行的实战代码,帮助读者掌握仓颉语言中的进程操控完整方案。

一、process 包定位与整体架构

process 包提供 Process 进程操作接口,主要包括进程创建、标准流获取、进程等待、进程信息查询等(见 process_package_overview.md)。包提供多平台统一操控能力,目前支持 Linux、macOS、Windows 与 HarmonyOS 四个平台。

从包结构看,process 包的核心 API 分为四层:

类别 名称 功能
类 Process 进程基类,提供进程操作相关功能
类 CurrentProcess (deprecated) 当前进程类,继承 Process,提供当前进程操作
类 SubProcess 子进程类,继承 Process,提供子进程操作
枚举 ProcessRedirect 创建进程时设置子进程标准流重定向模式
函数 execute / executeWithOutput / launch / findProcess 顶层便捷函数,创建/绑定进程
异常 ProcessException process 包的异常类,继承 IOException

其中三个类之间的继承关系为:CurrentProcess <: Process、SubProcess <: Process。整包在标准库中的定位可见 std_module_overview.md 的包列表。

版本演进提示:Process.current、CurrentProcess 及 Process.of、run、runOutput、start 等一批成员均标注为 deprecated(未来版本即将废弃),官方推荐迁移到 std.env 包的全局函数(如 getCommandLine()、getVariables()、getHomeDirectory())与 process 包新增的顶层函数(execute、executeWithOutput、launch、findProcess)上。新代码应优先采用新 API,详见下文各节。

二、class Process:进程基类

Process 类声明为 public open class Process,是可被继承的开放类,提供如下功能(见 process_package_classes.md):

  • 提供获取当前进程实例的功能(static prop current,已废弃);
  • 提供根据进程 id 绑定进程实例的功能(static func of,已废弃,顶层函数 findProcess 替代);
  • 提供根据输入信息创建子进程的功能(run、runOutput、start,已废弃,顶层函数 execute、executeWithOutput、launch 替代);
  • 提供获取进程信息的功能(pid、name、command 等属性);
  • 提供关闭进程的功能,允许设置是否强制关闭(terminate)。

2.1 进程信息查询属性

属性 签名 说明
pid public prop pid: Int64 获取进程 id(四平台均支持)
name public prop name: String 获取进程名,进程不存在或为僵尸进程时抛 ProcessException
command public prop command: String 获取进程命令,同样在进程不存在/僵尸进程时抛 ProcessException
startTime public prop startTime: DateTime 获取进程启动时间,获取失败时返回 DateTime.UnixEpoch
systemTime public prop systemTime: Duration 文档描述为获取进程启动时间,获取失败时返回 -1ms
userTime public prop userTime: Duration 文档描述为获取进程启动时间,获取失败时返回 -1ms
isAlive() public func isAlive(): Bool 返回进程是否存活,存活返回 true,否则 false

关于 systemTime / userTime:从属性命名看,二者分别对应进程的系统(内核态)CPU 时间与用户态 CPU 时间,类型均为 Duration;原文档功能描述为“获取进程启动时间,获取失败时返回 -1ms”(原文如此),实际语义以 SDK 版本实现为准。

2.2 已废弃的静态属性与进程绑定

public static prop current: CurrentProcess   // deprecated,使用 std.env 包的全局函数替代
public static func of(pid: Int64): Process   // deprecated,使用 findProcess(pid) 替代

static prop current 用于获取当前进程实例,未来版本即将废弃,改用 std.env 包的函数 替代。static func of(pid: Int64) 根据输入进程 id 绑定进程实例,异常规则如下:

  • IllegalArgumentException:输入进程 id 大于 Int32 最大值或小于 0 时抛出;
  • ProcessException:内存分配失败或 pid 对应的进程不存在时抛出。

2.3 已废弃的进程信息属性(平台限制明显)

属性 签名 平台说明
arguments public open prop arguments: Array<String> Windows 平台无法在非特权 API 下获取,暂不支持
commandLine public prop commandLine: Array<String> Windows 当前进程可获取,其他场景暂不支持;废弃后使用 getcommandline()
environment public prop environment: Map<String, String> 仅 Linux、HarmonyOS 支持;废弃后使用 getVariables()
workingDirectory public prop workingDirectory: Path Windows 当前进程可获取,其他场景暂不支持;废弃后使用 getHomeDirectory()

这些属性在进程不存在、对应进程为僵尸进程或平台不支持场景下,均抛出 ProcessException。各成员的四平台支持矩阵可对照 process_package_overview.md 中的兼容性表格(arguments、commandLine、environment、workingDirectory 均未覆盖全部四平台)。

2.4 进程终止:terminate 与 terminateAliveProcess

public func terminate(force!: Bool = false): Unit
protected open func terminateAliveProcess(pid: Int32, force: Bool): Unit

terminate 用于终止进程,force 为命名可选参数,默认为 false:

  • force = false:对应进程可以在释放资源后结束(优雅终止);
  • force = true:对应进程将被直接杀死(强制终止);
  • Windows 平台实现为强制关闭进程。

当进程不存在或不允许终止时抛出 ProcessException。terminateAliveProcess(pid, force) 是受保护的开放方法,供子类扩展指定进程的终止逻辑,参数 pid 为需要终止的进程 ID。

三、class CurrentProcess:当前进程操作(deprecated)

CurrentProcess 类声明为 public class CurrentProcess <: Process,继承 Process,提供对当前进程操作相关功能。官方已明确标注未来版本即将废弃,建议迁移到 std.env 包。其提供三类能力:

  • 获取当前进程标准流(stdIn、stdOut、stdErr);
  • 注册当前进程退出回调函数(atExit);
  • 当前进程退出机制,允许设置退出状态码(exit)。

3.1 标准流与环境路径属性

属性 签名 功能
stdIn public prop stdIn: InputStream 获取当前进程标准输入流
stdOut public prop stdOut: OutputStream 获取当前进程标准输出流
stdErr public prop stdErr: OutputStream 获取当前进程标准错误流
homeDirectory public prop homeDirectory: Path 获取 home 目录的路径(支持 Linux/Windows/macOS)
tempDirectory public prop tempDirectory: Path 获取临时目录路径:从环境变量中依次获取 TMPDIR、TMP、TEMP 和 TEMPDIR,若均不存在则默认返回 /tmp 目录(支持 Linux/Windows/macOS)

标准流的类型为 io 包 的 InputStream / OutputStream 接口;Path 类型来自 fs 包。

3.2 进程退出与退出回调

public func atExit(callback: () -> Unit): Unit
public func exit(code: Int64): Nothing
  • atExit(callback):注册回调函数,当前进程退出时执行注册函数。注意:请不要使用 C 语言 atexit 函数,避免出现不可期问题。
  • exit(code):进程退出函数,执行到此处直接结束当前进程,并通过入参 code 设置返回状态码(返回类型 Nothing)。

这两个能力在 std.env 包 中以同名全局函数 atExit / exit 提供,语义一致。

3.3 进程参数与环境变量操作

public prop arguments: Array<String>          // 当前进程参数列表
public func getEnv(k: String): Option<String>
public func removeEnv(k: String): Unit
public func setEnv(k: String, v: String): Unit
  • arguments:返回当前进程参数列表。例如当前进程命令行为 a.out ab cd ef,其中 a.out 是程序名,则返回列表包含 ab cd ef 三个元素。注意:使用 C 语言调用仓颉动态库时,通过 int SetCJCommandLineArgs(int argc, const char* argv[]) 设置的命令行参数,用 arguments 获取时会被舍弃第一个参数。
  • getEnv(k):获取指定名称的环境变量值,返回 Option<String>;参数 k 包含空字符时抛 IllegalArgumentException。
  • removeEnv(k):通过指定环境变量名称移除环境变量;参数 k 包含空字符时抛 IllegalArgumentException。
  • setEnv(k, v):设置一对环境变量,若设置同名环境变量,原始值将被覆盖;参数 k 或 v 包含空字符时抛 IllegalArgumentException。Windows 下如果传入的 v 是空字符串,会从环境中移除变量 k。

上述环境变量操作均有 std.env 包 的 getVariable、removeVariable、setVariable 函数作为替代(返回类型为 ?String,语义基本一致)。

四、class SubProcess:子进程操作

SubProcess 类声明为 public class SubProcess <: Process,继承 Process,提供对子进程操作相关功能:

  • 获取子进程标准流(stdIn、stdOut、stdErr);
  • 等待子进程执行并返回退出状态码,允许设置等待超时时长(wait);
  • 等待子进程执行并返回输出结果(包含正常、异常结果),允许设置超时时长(waitOutput)。

4.1 子进程标准流管道属性

属性 签名 功能
stdIn (deprecated) public prop stdIn: OutputStream 输出流,连接到子进程标准输入流;废弃后使用 stdInPipe
stdInPipe public prop stdInPipe: OutputStream 输出流,连接到子进程标准输入流
stdOut (deprecated) public prop stdOut: InputStream 输入流,连接到子进程标准输出流;废弃后使用 stdOutPipe
stdOutPipe public prop stdOutPipe: InputStream 输入流,连接到子进程标准输出流
stdErr (deprecated) public prop stdErr: InputStream 输入流,连接到子进程标准错误流;废弃后使用 stdErrPipe
stdErrPipe public prop stdErrPipe: InputStream 输入流,连接到子进程标准错误流

注意方向性:子进程的标准输入对父进程而言是输出流(父进程通过它向子进程写数据),而子进程的标准输出/标准错误对父进程而言是输入流(父进程通过它读取子进程结果)。只有创建子进程时对应标准流指定为 ProcessRedirect.Pipe 模式,这些管道属性才能读写数据(详见第五节)。

4.2 等待子进程:wait 与 waitOutput

public func wait(timeout!: ?Duration = None): Int64
public func waitOutput(): (Int64, Array<Byte>, Array<Byte>)

wait(timeout:) 阻塞当前进程等待子进程任务执行完成并返回退出状态码。超时时间处理机制:

  • 未传参、timeout 值为 None 或值小于等于 Duration.Zero 时,阻塞等待直至子进程执行返回;
  • timeout 值大于 Duration.Zero 时,阻塞等待子进程执行返回或等待超时后抛出 TimeoutException。

返回值为 Int64:若子进程正常退出,返回子进程退出码;若子进程被信号杀死,返回导致子进程终止的信号编号。

waitOutput() 阻塞等待子进程执行完成,返回三元组 (退出状态, 标准输出字节数组, 标准错误字节数组)。当子进程不存在或标准流读取异常时抛 ProcessException。

死锁警示:对于需要操作标准流的场景(Pipe 模式),使用者需要优先处理标准流,避免子进程标准流缓冲区满后调用本函数产生死锁。waitOutput 同样不适用于输出流、错误流包含大量输出的场景,此时建议通过 SubProcess 的标准流属性(stdOutPipe / stdErrPipe)结合 wait 函数自行处理。

五、ProcessRedirect 枚举:标准流重定向模式

创建进程时,通过 stdIn、stdOut、stdErr 三个命名可选参数设置子进程标准流的重定向模式,取值来自 ProcessRedirect 枚举:

public enum ProcessRedirect {
    | Inherit
    | Pipe
    | FromFile(File)
    | Discard
}
枚举值 语义 标准流属性可读写性
Inherit 子进程标准流继承当前进程的标准流(默认值) 不可读取或写入
Pipe 子进程标准流重定向至管道,并通过管道与当前进程连接 可通过 SubProcess 标准流属性读取或写入
FromFile(File) 子进程标准流重定向至指定文件:标准输入从文件读取,标准输出/错误写入文件。重定向文件需保证存在且未关闭,否则不允许重定向 不可读取或写入
Discard 子进程标准流被丢弃 不可读取或写入

其中 FromFile(File) 的 File 为 fs 包 中存在且未关闭的文件实例。

六、顶层函数:创建与绑定进程的新 API

process 包在顶层提供了四个全局函数(见 process_package_funcs.md),分别替代 Process.run、Process.runOutput、Process.start 与 Process.of:

6.1 execute:运行子进程并等待退出

public func execute(command: String,
                    arguments: Array<String>,
                    workingDirectory!: ?Path = None,
                    environment!: ?Map<String, String> = None,
                    stdIn!: ProcessRedirect = Inherit,
                    stdOut!: ProcessRedirect = Inherit,
                    stdErr!: ProcessRedirect = Inherit,
                    timeout!: ?Duration = None): Int64

根据输入参数创建并运行一个子进程,等待该子进程运行完毕并返回退出状态。各参数约束如下:

参数 默认值 约束
command 必填 指定子进程命令,不允许包含空字符
arguments 必填 子进程参数,数组中不允许字符串包含空字符
workingDirectory None(继承当前进程工作路径) 路径必须为存在的目录,不允许为空路径或包含空字符
environment None(继承当前进程环境变量) key 不允许包含空字符或 '=',value 不允许包含空字符
stdIn / stdOut / stdErr Inherit 见 ProcessRedirect 枚举
timeout None(不超时) 指定为 0 或负值时表示不超时

返回值 Int64:子进程正常退出返回退出码,被信号杀死返回导致终止的信号编号。

异常:

  • IllegalArgumentException:当入参 command 含空字符,arguments 数组中字符串含空字符,workingDirectory 不是存在的目录/为空路径/含空字符,environment 的 key 含空字符或 '=' 或 value 含空字符,或 stdIn/stdOut/stdErr 为文件模式但文件已被关闭或删除时抛出;
  • ProcessException:内存分配失败、command 对应的命令不存在或等待超时时抛出。

Windows 平台注意:在子进程执行完成后立即删除子进程的可执行文件可能删除失败并抛出 Access is denied 异常。如遇该问题,可在一小段延迟后重新尝试删除该文件。

6.2 executeWithOutput:运行子进程并捕获输出

public func executeWithOutput(command: String,
                              arguments: Array<String>,
                              workingDirectory!: ?Path = None,
                              environment!: ?Map<String, String> = None,
                              stdIn!: ProcessRedirect = Inherit,
                              stdOut!: ProcessRedirect = Pipe,
                              stdErr!: ProcessRedirect = Pipe): (Int64, Array<Byte>, Array<Byte>)

与 execute 参数规则一致,区别在于 stdOut、stdErr 默认值均为 Pipe,返回值三元组包含退出状态、标准输出结果、标准错误结果。输出流、错误流包含大量输出的场景不适用于本函数,建议通过 SubProcess 标准流属性结合 wait 自行处理。

6.3 launch:创建子进程实例

public func launch(command: String,
                   arguments: Array<String>,
                   workingDirectory!: ?Path = None,
                   environment!: ?Map<String, String> = None,
                   stdIn!: ProcessRedirect = Inherit,
                   stdOut!: ProcessRedirect = Inherit,
                   stdErr!: ProcessRedirect = Inherit): SubProcess

根据输入参数创建并运行一个子进程,返回 SubProcess 实例。调用 launch 创建子进程后,必须调用 wait 或 waitOutput 函数,否则该子进程结束后成为的僵尸进程的资源不会被回收。异常规则同 execute(内存分配失败或命令不存在时抛 ProcessException)。

6.4 findProcess:按 pid 绑定进程

public func findProcess(pid: Int64): Process

根据输入进程 id 绑定并返回一个 Process 实例,用于操控任意已存在进程(非当前进程创建的子进程)。异常规则与 Process.of 相同:pid 大于 Int32 最大值或小于 0 时抛 IllegalArgumentException;内存分配失败或 pid 对应的进程不存在时抛 ProcessException。

七、实战示例

仓库在 process_samples 中提供了两个可运行示例。

7.1 任意进程相关操作(不支持 Windows)

来自 process_sample.md:

import std.process.*

main(): Int64 {
    let echoProcess: SubProcess = launch("sleep", "10s")
    let ofProcess: Process = findProcess(echoProcess.pid)
    println(ofProcess.pid)
    println(ofProcess.name)
    println(ofProcess.command)
    ofProcess.terminate(force: true)
    return 0
}

该示例演示了完整调用链:用 launch 创建子进程 → 通过 findProcess(pid) 绑定同一进程实例 → 查询其 pid、name、command → 用 terminate(force: true) 强制终止。运行结果可能如下:

70753
sleep
sleep

7.2 子进程相关操作:管道读取与强制终止(不支持 Windows)

来自 process_subprocess_sample.md:

import std.process.*
import std.io.*
import std.fs.*

// 以Linux平台相关命令举例说明, 以下用例需要提前创建 “/root/code/Process/test” 目录
main(): Int64 {
    let sleepProcess: SubProcess = launch("sleep", "10s", workingDirectory: Path("/root/code/Process/test"))
    println(sleepProcess.pid)
    println(sleepProcess.name)
    println(sleepProcess.command)
    sleepProcess.terminate(force: true)
    let rtnCode = sleepProcess.wait()
    println("sleepProcess rtnCode: ${rtnCode}")

    let echoProcess: SubProcess = launch("echo", "hello cangjie!", stdOut: ProcessRedirect.Pipe)
    let strReader: StringReader<InputStream> = StringReader(echoProcess.stdOutPipe)
    println(strReader.readToEnd())
    return 0
}

要点解析:

  1. launch + 命名可选参数:workingDirectory: Path("/root/code/Process/test") 指定子进程工作目录(需为已存在目录);
  2. 强制终止 + wait 回收:terminate(force: true) 强制杀死 sleep 进程后调用 wait() 回收资源并获取退出状态(示例中返回信号编号 9,即 SIGKILL);
  3. Pipe 模式读取输出:launch("echo", "hello cangjie!", stdOut: ProcessRedirect.Pipe) 将子进程标准输出重定向为管道,父进程通过 stdOutPipe 属性配合 io 包 的 StringReader 读取全部内容。

运行结果可能如下:

65953
sleep
sleep
sleepProcess rtnCode: 9
hello cangjie!

7.3 实战建议:优先使用新 API

对照上面两个示例,推荐的新代码组合是:

  • 需要“运行并等待退出码”→ execute(...);
  • 需要“运行并捕获 stdout/stderr”→ executeWithOutput(...);
  • 需要“异步启动子进程、交互标准流、超时控制”→ launch(...) + SubProcess.wait(timeout:);
  • 需要“查询/操控已存在进程”→ findProcess(pid) + Process 信息属性 + terminate();
  • 需要“当前进程信息与环境变量”→ 迁移到 std.env 包 的 getProcessId()、getCommand()、getWorkingDirectory()、getVariable()、setVariable()、getStdIn()/getStdOut() 等函数。

八、异常体系:ProcessException

process 包的统一异常类为 ProcessException,声明如下(见 process_package_exceptions.md):

public class ProcessException <: IOException {
    public init(message: String)
}

它继承 io 包 的 IOException,构造时传入异常提示信息 message。ProcessException 在以下典型场景抛出:

  • 进程不存在或对应进程为僵尸进程(name、command、commandLine、environment、workingDirectory 等属性读取);
  • command 对应的命令不存在(execute、executeWithOutput、launch、run、start);
  • 内存分配失败、子进程不存在、标准流读取异常;
  • 进程不存在或不允许终止(terminate);
  • 等待子进程超时场景则抛出 core 包 的 TimeoutException。

参数校验类异常统一为 IllegalArgumentException(空字符、非法路径、非法环境变量键等),见 core 包异常文档。

九、小结

仓颉标准库 std.process 为开发者提供了完整、多平台统一的进程操控能力:Process 承担进程信息查询与终止,SubProcess 扩展了管道标准流与等待机制,CurrentProcess 覆盖当前进程的标准流、退出回调与环境变量操作,ProcessRedirect 枚举精确控制三种标准流的重定向行为。随着 Process.current 与 CurrentProcess 等旧 API 被标记废弃,新代码应优先采用 execute / executeWithOutput / launch / findProcess 四个顶层函数,并将当前进程相关能力迁移到 std.env 包。掌握上述 API 与平台差异后,无论是构建构建脚本、进程管理工具,还是实现需要与子进程双向交互的命令行应用,都可以在仓颉中直接落地。

相关文档索引

登录后查看全文
CangjieCorpus