跳转到内容
标准库Zig 0.17.0官方原文
源码std/process.zig

第 1 行

std.process.abort

函数

第 808 行

导致进程异常终止。

若链接 libc,则调用 std.c.abort。否则先发送 SIGABRT,再发送 SIGKILL。

若当前存在 SIGABRT 信号处理程序,则调用它。

pub fn abort() noreturn

std.process.abort.abort_entered

变量

第 834 行

bool

std.process.Allocator

别名

第 11 行

别名目标 std.mem.Allocator

std.process.ArgExpansion

容器

第 329 行

字段

expand
no_expand

std.process.Args

别名

第 20 行

别名目标 std.process.Args

std.process.assert

别名

第 12 行

别名目标 std.debug.assert

std.process.builtin

常量

第 1 行

std.process.can_replace

常量

第 256 行

返回目标操作系统是否支持替换当前进程映像。 若为 false,则调用 replace 或 replaceFile 函数将返回 error.OperationUnsupported。

std.process.can_spawn

常量

第 262 行

表示是否支持创建子进程。

std.process.Child

别名

第 19 行

别名目标 std.process.Child

std.process.cleanExit

函数

第 648 行

表明将以成功退出码终止的意图。

在调试构建中不执行任何操作,以便测试调用代码的清理 机制,同时使外部工具能够准确检查资源 泄漏。在发布构建中,以零退出码调用 exit, 不再返回。

pub fn cleanExit(io: Io) void

参数

io: Io

std.process.currentPath

函数

第 74 行

在 Windows 上,结果以 WTF-8 编码。 在其他平台上,结果是不指定编码的不透明字节序列。

pub fn currentPath(io: Io, buffer: []u8) CurrentPathError!usize

参数

io: Io
buffer: []u8

错误

Canceled Cancelable

调用方请求停止异步操作。

CurrentDirUnlinked

在 Windows 上不可能发生。在 WASI 上始终返回。

NameTooLong

缓冲区过小,无法容纳当前路径。

PathExceedsLimit

受底层 libc 或系统调用实现限制,无法获取当前路径。换用更大缓冲区重试也不会成功。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.process.currentPathAlloc

函数

第 87 行

使用大小为 max_path_bytes 的缓冲区调用 currentPath 的快捷方式。

Windows 上,结果采用 WTF-8 编码。 其他平台上,结果是不指定 编码的不透明字节序列。

调用方拥有返回内存的所有权。

pub fn currentPathAlloc(io: Io, allocator: Allocator) CurrentPathAllocError![:0]u8

参数

io: Io
allocator: Allocator

错误

Canceled Cancelable

调用方请求停止异步操作。

CurrentDirUnlinked CurrentPathError

在 Windows 上不可能发生。在 WASI 上始终返回。

NameTooLong CurrentPathError

缓冲区过小,无法容纳当前路径。

OutOfMemory Error
PathExceedsLimit CurrentPathError

受底层 libc 或系统调用实现限制,无法获取当前路径。换用更大缓冲区重试也不会成功。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

用法示例

test currentPathAlloc {
    const cwd = try currentPathAlloc(testing.io, testing.allocator);
    testing.allocator.free(cwd);
}

std.process.CurrentPathAllocError

错误集合

第 78 行

错误

Canceled Cancelable

调用方请求停止异步操作。

CurrentDirUnlinked CurrentPathError

在 Windows 上不可能发生。在 WASI 上始终返回。

NameTooLong CurrentPathError

缓冲区过小,无法容纳当前路径。

OutOfMemory Error
PathExceedsLimit CurrentPathError

受底层 libc 或系统调用实现限制,无法获取当前路径。换用更大缓冲区重试也不会成功。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.process.CurrentPathError

错误集合

第 60 行

错误

Canceled Cancelable

调用方请求停止异步操作。

CurrentDirUnlinked

在 Windows 上不可能发生。在 WASI 上始终返回。

NameTooLong

缓冲区过小,无法容纳当前路径。

PathExceedsLimit

受底层 libc 或系统调用实现限制,无法获取当前路径。换用更大缓冲区重试也不会成功。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.process.Dir

别名

第 6 行

别名目标 std.Io.Dir

std.process.Environ

别名

第 21 行

别名目标 std.process.Environ

std.process.executableDirPath

函数

第 779 行

获取包含当前可执行文件的目录路径。

返回 out_buffer 中的索引。

在 Windows 上,结果以 WTF-8 编码。 在其他平台上,结果是不指定编码的不透明字节序列。

pub fn executableDirPath(io: Io, out_buffer: []u8) ExecutablePathError!usize

参数

io: Io
out_buffer: []u8

错误

AccessDenied ExecutablePathBaseError
AntivirusInterference ExecutablePathBaseError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName ExecutablePathBaseError
Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy ExecutablePathBaseError
FileNotFound ExecutablePathBaseError
FileSystem ExecutablePathBaseError
FileTooBig ExecutablePathBaseError
InputOutput ExecutablePathBaseError
IsDir ExecutablePathBaseError
NameTooLong
NetworkNotFound ExecutablePathBaseError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice ExecutablePathBaseError
NoSpaceLeft ExecutablePathBaseError
NotDir ExecutablePathBaseError
NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

操作系统不支持可执行文件获取自身 路径。

PathAlreadyExists ExecutablePathBaseError
PermissionDenied ExecutablePathBaseError
PipeBusy ExecutablePathBaseError
ProcessFdQuotaExceeded ExecutablePathBaseError
ProcessNotFound ExecutablePathBaseError
SymLinkLoop ExecutablePathBaseError
SystemFdQuotaExceeded ExecutablePathBaseError
SystemResources ExecutablePathBaseError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume ExecutablePathBaseError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

std.process.executableDirPathAlloc

函数

第 787 行

与 executableDirPath 相同,但会为结果分配内存。

pub fn executableDirPathAlloc(io: Io, allocator: Allocator) ExecutablePathAllocError![]u8

参数

io: Io
allocator: Allocator

错误

AccessDenied ExecutablePathBaseError
AntivirusInterference ExecutablePathBaseError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName ExecutablePathBaseError
Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy ExecutablePathBaseError
FileNotFound ExecutablePathBaseError
FileSystem ExecutablePathBaseError
FileTooBig ExecutablePathBaseError
InputOutput ExecutablePathBaseError
IsDir ExecutablePathBaseError
NetworkNotFound ExecutablePathBaseError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice ExecutablePathBaseError
NoSpaceLeft ExecutablePathBaseError
NotDir ExecutablePathBaseError
NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

操作系统不支持可执行文件获取自身 路径。

OutOfMemory Error
PathAlreadyExists ExecutablePathBaseError
PermissionDenied ExecutablePathBaseError
PipeBusy ExecutablePathBaseError
ProcessFdQuotaExceeded ExecutablePathBaseError
ProcessNotFound ExecutablePathBaseError
SymLinkLoop ExecutablePathBaseError
SystemFdQuotaExceeded ExecutablePathBaseError
SystemResources ExecutablePathBaseError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume ExecutablePathBaseError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

std.process.executablePath

函数

第 769 行

获取当前可执行文件的路径,并解析符号链接。

若当前可执行文件在进程启动后 被删除,此函数可能返回错误。

返回值是 out_buffer 的切片。

Windows 上,结果采用 WTF-8 编码。 其他平台上,结果是不指定编码的不透明字节序列。

Linux 上依赖已挂载的 procfs。若当前执行的二进制文件 已被删除,文件路径类似于 "/a/b/c/exe (deleted)"。

另请参见:

pub fn executablePath(io: Io, out_buffer: []u8) ExecutablePathError!usize

参数

io: Io
out_buffer: []u8

错误

AccessDenied ExecutablePathBaseError
AntivirusInterference ExecutablePathBaseError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName ExecutablePathBaseError
Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy ExecutablePathBaseError
FileNotFound ExecutablePathBaseError
FileSystem ExecutablePathBaseError
FileTooBig ExecutablePathBaseError
InputOutput ExecutablePathBaseError
IsDir ExecutablePathBaseError
NameTooLong
NetworkNotFound ExecutablePathBaseError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice ExecutablePathBaseError
NoSpaceLeft ExecutablePathBaseError
NotDir ExecutablePathBaseError
NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

操作系统不支持可执行文件获取自身 路径。

PathAlreadyExists ExecutablePathBaseError
PermissionDenied ExecutablePathBaseError
PipeBusy ExecutablePathBaseError
ProcessFdQuotaExceeded ExecutablePathBaseError
ProcessNotFound ExecutablePathBaseError
SymLinkLoop ExecutablePathBaseError
SystemFdQuotaExceeded ExecutablePathBaseError
SystemResources ExecutablePathBaseError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume ExecutablePathBaseError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

std.process.executablePathAlloc

函数

第 742 行

pub fn executablePathAlloc(io: Io, allocator: Allocator) ExecutablePathAllocError![:0]u8

参数

io: Io
allocator: Allocator

错误

AccessDenied ExecutablePathBaseError
AntivirusInterference ExecutablePathBaseError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName ExecutablePathBaseError
Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy ExecutablePathBaseError
FileNotFound ExecutablePathBaseError
FileSystem ExecutablePathBaseError
FileTooBig ExecutablePathBaseError
InputOutput ExecutablePathBaseError
IsDir ExecutablePathBaseError
NetworkNotFound ExecutablePathBaseError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice ExecutablePathBaseError
NoSpaceLeft ExecutablePathBaseError
NotDir ExecutablePathBaseError
NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

操作系统不支持可执行文件获取自身 路径。

OutOfMemory Error
PathAlreadyExists ExecutablePathBaseError
PermissionDenied ExecutablePathBaseError
PipeBusy ExecutablePathBaseError
ProcessFdQuotaExceeded ExecutablePathBaseError
ProcessNotFound ExecutablePathBaseError
SymLinkLoop ExecutablePathBaseError
SystemFdQuotaExceeded ExecutablePathBaseError
SystemResources ExecutablePathBaseError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume ExecutablePathBaseError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

std.process.ExecutablePathAllocError

错误集合

第 740 行

错误

AccessDenied ExecutablePathBaseError
AntivirusInterference ExecutablePathBaseError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName ExecutablePathBaseError
Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy ExecutablePathBaseError
FileNotFound ExecutablePathBaseError
FileSystem ExecutablePathBaseError
FileTooBig ExecutablePathBaseError
InputOutput ExecutablePathBaseError
IsDir ExecutablePathBaseError
NetworkNotFound ExecutablePathBaseError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice ExecutablePathBaseError
NoSpaceLeft ExecutablePathBaseError
NotDir ExecutablePathBaseError
NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

操作系统不支持可执行文件获取自身 路径。

OutOfMemory Error
PathAlreadyExists ExecutablePathBaseError
PermissionDenied ExecutablePathBaseError
PipeBusy ExecutablePathBaseError
ProcessFdQuotaExceeded ExecutablePathBaseError
ProcessNotFound ExecutablePathBaseError
SymLinkLoop ExecutablePathBaseError
SystemFdQuotaExceeded ExecutablePathBaseError
SystemResources ExecutablePathBaseError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume ExecutablePathBaseError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

std.process.ExecutablePathBaseError

错误集合

第 703 行

错误

AccessDenied
AntivirusInterference

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName
Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy
FileNotFound
FileSystem
FileTooBig
InputOutput
IsDir
NetworkNotFound

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice
NoSpaceLeft
NotDir
NotLink
OperationUnsupported

操作系统不支持可执行文件获取自身 路径。

PathAlreadyExists
PermissionDenied
PipeBusy
ProcessFdQuotaExceeded
ProcessNotFound
SymLinkLoop
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

std.process.ExecutablePathError

错误集合

第 751 行

错误

AccessDenied ExecutablePathBaseError
AntivirusInterference ExecutablePathBaseError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName ExecutablePathBaseError
Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy ExecutablePathBaseError
FileNotFound ExecutablePathBaseError
FileSystem ExecutablePathBaseError
FileTooBig ExecutablePathBaseError
InputOutput ExecutablePathBaseError
IsDir ExecutablePathBaseError
NameTooLong
NetworkNotFound ExecutablePathBaseError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice ExecutablePathBaseError
NoSpaceLeft ExecutablePathBaseError
NotDir ExecutablePathBaseError
NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

操作系统不支持可执行文件获取自身 路径。

PathAlreadyExists ExecutablePathBaseError
PermissionDenied ExecutablePathBaseError
PipeBusy ExecutablePathBaseError
ProcessFdQuotaExceeded ExecutablePathBaseError
ProcessNotFound ExecutablePathBaseError
SymLinkLoop ExecutablePathBaseError
SystemFdQuotaExceeded ExecutablePathBaseError
SystemResources ExecutablePathBaseError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume ExecutablePathBaseError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

std.process.exit

函数

第 865 行

以指定状态码退出程序的全部线程。

pub fn exit(status: u8) noreturn

参数

status: u8

std.process.fatal

函数

第 698 行

记录错误,然后以退出码 1 终止进程。

pub fn fatal(comptime format: []const u8, format_arguments: anytype) noreturn

参数

format: []const u8

std.process.File

别名

第 7 行

别名目标 std.Io.File

std.process.fs

别名

第 8 行

别名目标 std.fs

std.process.getBaseAddress

函数

第 234 行

pub fn getBaseAddress() usize

std.process.getUserInfo

函数

第 104 行

根据用户名获取 uid 的 POSIX 函数。

pub fn getUserInfo(io: Io, name: []const u8) !UserInfo

参数

io: Io
name: []const u8

std.process.Init

容器

第 31 行

一组标准的、预先初始化的实用接口,供程序使用。这是 main 函数第一个参数的类型。 需要更高灵活性的应用程序可以改为接受 Init.Minimal。

完成 https://github.com/ziglang/zig/issues/24510 后,还将允许 main 函数的第二个参数为自定义结构体,其中包含自动解析的命令行参数。

字段

minimal: Minimal

Init 是 Minimal 的超集;后者包含在此处。

arena: *std.heap.ArenaAllocator

整个进程存活期间的永久存储,退出时自动 清理。线程安全。

gpa: Allocator

默认选择的通用分配器,用于临时堆分配。 调试模式下会在可能时启用内存泄漏检查。 线程安全。

io: Io

根据目标配置选择合适的默认 Io 实现。 调试模式下会尽可能启用泄漏检查。

environ_map: *Environ.Map

环境变量,使用 gpa 初始化。非线程安全。

preopens: Preopens

父进程提供的具名文件。主要用于 WASI, 但也可在其他系统上模拟与标准输入输出相关的行为。

std.process.Init.Minimal

容器

第 52 行

可作为 main 函数首个参数、替代 Init 的类型。

字段

environ: Environ

环境变量。

args: Args

命令行参数。

std.process.Io

别名

第 5 行

别名目标 std.Io

std.process.lockMemory

函数

第 964 行

请求将调用进程的一部分虚拟地址空间保留在 RAM 中, 防止该内存被换出到交换区。

对应 libc 中的 "mlock" 或 "mlock2"。

另见:

  • unlockMemory
pub fn lockMemory(memory: []align(std.heap.page_size_min) const u8, options: LockMemoryOptions) LockMemoryError!void

参数

memory: []align(std.heap.page_size_min) const u8
options: LockMemoryOptions

错误

LockedMemoryLimitExceeded
PermissionDenied
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnsupportedOperation

用法示例

test lockMemory {
    lockMemory(&test_page, .{}) catch return error.SkipZigTest;
    unlockMemory(&test_page) catch return error.SkipZigTest;
}

std.process.lockMemoryAll

函数

第 1023 行

pub fn lockMemoryAll(options: LockMemoryAllOptions) LockMemoryError!void

参数

错误

LockedMemoryLimitExceeded
PermissionDenied
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnsupportedOperation

用法示例

test lockMemoryAll {
    lockMemoryAll(.{ .current = true }) catch return error.SkipZigTest;
    unlockMemoryAll() catch return error.SkipZigTest;
}

std.process.LockMemoryAllOptions

容器

第 1016 行

字段

current: bool = false
future: bool = false
on_fault: bool = false

断言与 current 或 future 至少一项一起使用。

std.process.LockMemoryError

错误集合

第 943 行

错误

LockedMemoryLimitExceeded
PermissionDenied
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnsupportedOperation

std.process.LockMemoryOptions

容器

第 950 行

字段

on_fault: bool = false

锁定当前驻留页面,并标记整个范围, 以便剩余非驻留页面因缺页而填充时 也被锁定。

std.process.math

别名

第 10 行

别名目标 std.math

std.process.max_path_bytes

别名

第 17 行

别名目标 std.fs.max_path_bytes

std.process.mem

别名

第 9 行

别名目标 std.mem

std.process.MemoryProtection

容器

第 1074 行

字段

read: bool = false
write: bool = false
execute: bool = false

std.process.native_os

常量

第 2 行

std.process.openExecutable

函数

第 798 行

pub fn openExecutable(io: Io, flags: Dir.OpenFileOptions) OpenExecutableError!File

参数

io: Io
flags: Dir.OpenFileOptions

错误

AccessDenied OpenError

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy OpenError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileSystem ExecutablePathBaseError
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

InputOutput ExecutablePathBaseError
IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound OpenError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice OpenError
NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

操作系统不支持可执行文件获取自身 路径。

PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied OpenError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ProcessNotFound ExecutablePathBaseError
ReadOnlyFileSystem OpenError
SymLinkLoop OpenError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume ExecutablePathBaseError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.process.OpenExecutableError

错误集合

第 796 行

错误

AccessDenied OpenError

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy OpenError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileSystem ExecutablePathBaseError
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

InputOutput ExecutablePathBaseError
IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound OpenError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice OpenError
NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

NotLink ExecutablePathBaseError
OperationUnsupported ExecutablePathBaseError

操作系统不支持可执行文件获取自身 路径。

PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied OpenError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ProcessNotFound ExecutablePathBaseError
ReadOnlyFileSystem OpenError
SymLinkLoop OpenError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume ExecutablePathBaseError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.process.posix

别名

第 14 行

别名目标 std.posix

std.process.posixGetUserInfo

函数

第 127 行

TODO: 此处读取 /etc/passwd,但用户/标识映射有时位于 NIS、AD 等其他来源。 参见 man nss,或查看 id myuser 的 strace。

pub fn posixGetUserInfo(io: Io, name: []const u8) !UserInfo

参数

io: Io
name: []const u8

std.process.posixGetUserInfoPasswdStream

函数

第 139 行

fn posixGetUserInfoPasswdStream(name: []const u8, reader: *std.Io.Reader) !UserInfo

参数

name: []const u8
reader: *std.Io.Reader

std.process.Preopens

别名

第 22 行

别名目标 std.process.Preopens

std.process.protectMemory

函数

第 1080 行

pub fn protectMemory(memory: []align(std.heap.page_size_min) u8, protection: MemoryProtection) ProtectMemoryError!void

参数

memory: []align(std.heap.page_size_min) u8
protection: MemoryProtection

错误

AccessDenied

无法授予此内存指定的访问权限。例如, 将只有只读访问权限的文件映射到内存后, 再用 protectMemory 将其标记为可写,就可能出现此情况。

OutOfMemory

更改某个内存区域的保护属性将导致 具有不同属性的映射总数超过允许的 最大值。

PermissionDenied

若指定区域包含此前通过 mimmutable 函数 标记为不可变的任何页面,OpenBSD 将拒绝 更改其内存保护。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnsupportedOperation

用法示例

test protectMemory {
    protectMemory(&test_page, .{}) catch return error.SkipZigTest;
    protectMemory(&test_page, .{ .read = true, .write = true }) catch return error.SkipZigTest;
}

std.process.ProtectMemoryError

错误集合

第 1058 行

错误

AccessDenied

无法授予此内存指定的访问权限。例如, 将只有只读访问权限的文件映射到内存后, 再用 protectMemory 将其标记为可写,就可能出现此情况。

OutOfMemory

更改某个内存区域的保护属性将导致 具有不同属性的映射总数超过允许的 最大值。

PermissionDenied

若指定区域包含此前通过 mimmutable 函数 标记为不可变的任何页面,OpenBSD 将拒绝 更改其内存保护。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnsupportedOperation

std.process.raiseFileDescriptorLimit

函数

第 658 行

请求允许同时打开更多文件描述符。

在某些系统上,这会在出现 ProcessFdQuotaExceeded 错误之前提高限制。在其他系统上,不执行任何操作。

pub fn raiseFileDescriptorLimit() void

用法示例

test raiseFileDescriptorLimit {
    raiseFileDescriptorLimit();
}

std.process.replace

函数

第 325 行

以被执行进程替换当前进程映像。若此 函数成功,则不返回。

不得在 fork() 的子进程中调用此函数。

pub fn replace(io: Io, options: ReplaceOptions) ReplaceError

参数

io: Io
options: ReplaceOptions

std.process.ReplaceError

错误集合

第 267 行

错误

AccessDenied
BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

FileBusy
FileNotFound
FileSystem
InvalidExe
IsDir
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NotDir
OperationUnsupported

目标操作系统无法用新的进程映像替换当前映像。

OutOfMemory Error
PermissionDenied
ProcessFdQuotaExceeded
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.process.ReplaceOptions

容器

第 284 行

字段

exe: Exe = .detect
argv: []const []const u8
cwd: Child.Cwd = .inherit

设置此项,可在创建子进程时更改当前工作目录。

environ_map: ?*const Environ.Map = null

如果提供,则替换环境。此处的 PATH 值 绝不会用于解析 argv[0]。

expand_arg0: ArgExpansion = .no_expand
inherit_dirs: []const Dir = &.{}
inherit_files: []const File = &.{}
start_suspended: bool = false

以挂起状态启动子进程。 在 Posix 系统上,以如同已发送 SIGSTOP 的状态启动。

std.process.ReplaceOptions.Exe

容器

第 302 行

字段

detect

argv[0] 为要执行的程序名称。若它尚不是 文件路径(即包含 '/',原文如此),则根据父环境中的 PATH 将其解析为文件路径。

search

argv[0] 是待执行程序的名称,根据父进程环境中的 PATH 解析为文件路径。

path: Dir

argv[0] 是要执行程序的文件路径,相对于 Dir 载荷。 它始终被视为文件路径,即使不包含 '/'。

file: File

File 载荷是要执行的程序。

explicit: struct { dir: Dir, path: []const u8 }

path 是要执行程序的文件路径,相对于 dir。 它始终被视为文件路径,即使不包含 '/'。

std.process.run

函数

第 507 行

生成子进程,等待其退出并收集 stdout、stderr,然后返回。 成功时,调用方拥有 result.stdout 和 result.stderr 内存的所有权。

pub fn run(gpa: Allocator, io: Io, options: RunOptions) RunError!RunResult

参数

gpa: Allocator
io: Io
options: RunOptions

错误

AccessDenied OpenError

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

ConcurrencyUnavailable ConcurrentError

可能由资源耗尽等临时情况引起,也可能因为 Io 实现不支持并发。

ConnectionResetByPeer UnendingError
DeviceBusy OpenError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileSystem SpawnError
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

InputOutput UnendingError
InvalidBatchScriptArg SpawnError

仅限 Windows。执行 .bat 或 .cmd 脚本时,参数中不允许 NUL(U+0000)、LF(U+000A)和 CR(U+000D)。

  • NUL 与 LF 表示参数结束,其后的内容在执行后会丢失。
  • CR 会被 cmd.exe 移除,因此执行后所有 CR 码点都会丢失。
InvalidExe SpawnError
InvalidName SpawnError
InvalidProcessGroupId SpawnError
InvalidUserId SpawnError
InvalidWtf8 SpawnError

仅限 Windows。提供的 cwd 或 argv 为无效 WTF-8。 https://wtf-8.codeberg.page/

IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
LockViolation UnendingError

由于锁定而无法读取文件。根据 Io 实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。

NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound OpenError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice SpawnError

仅限 POSIX。选择了 StdIo.ignore,且打开 /dev/null 时返回 ENODEV。

NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

NotOpenForReading UnendingError

打开文件时未授予读取能力。

OperationUnsupported SpawnError

操作系统不支持创建子进程。

OutOfMemory SpawnError
PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied SpawnError
PipeBusy OpenError
ProcessAlreadyExec SpawnError

尝试更改调用进程某个子进程的 进程组 ID,但该子进程已经执行 映像替换。

ProcessFdQuotaExceeded SpawnError
ReadOnlyFileSystem OpenError
ResourceLimitReached SpawnError
SocketUnconnected UnendingError
StreamTooLong
SymLinkLoop SpawnError
SystemFdQuotaExceeded SpawnError
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Timeout Error
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume SpawnError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.process.RunError

错误集合

第 466 行

错误

AccessDenied OpenError

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

ConcurrencyUnavailable ConcurrentError

可能由资源耗尽等临时情况引起,也可能因为 Io 实现不支持并发。

ConnectionResetByPeer UnendingError
DeviceBusy OpenError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileSystem SpawnError
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

InputOutput UnendingError
InvalidBatchScriptArg SpawnError

仅限 Windows。执行 .bat 或 .cmd 脚本时,参数中不允许 NUL(U+0000)、LF(U+000A)和 CR(U+000D)。

  • NUL 与 LF 表示参数结束,其后的内容在执行后会丢失。
  • CR 会被 cmd.exe 移除,因此执行后所有 CR 码点都会丢失。
InvalidExe SpawnError
InvalidName SpawnError
InvalidProcessGroupId SpawnError
InvalidUserId SpawnError
InvalidWtf8 SpawnError

仅限 Windows。提供的 cwd 或 argv 为无效 WTF-8。 https://wtf-8.codeberg.page/

IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
LockViolation UnendingError

由于锁定而无法读取文件。根据 Io 实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。

NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound OpenError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice SpawnError

仅限 POSIX。选择了 StdIo.ignore,且打开 /dev/null 时返回 ENODEV。

NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

NotOpenForReading UnendingError

打开文件时未授予读取能力。

OperationUnsupported SpawnError

操作系统不支持创建子进程。

OutOfMemory SpawnError
PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied SpawnError
PipeBusy OpenError
ProcessAlreadyExec SpawnError

尝试更改调用进程某个子进程的 进程组 ID,但该子进程已经执行 映像替换。

ProcessFdQuotaExceeded SpawnError
ReadOnlyFileSystem OpenError
ResourceLimitReached SpawnError
SocketUnconnected UnendingError
StreamTooLong
SymLinkLoop SpawnError
SystemFdQuotaExceeded SpawnError
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Timeout Error
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume SpawnError

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.process.RunOptions

容器

第 470 行

字段

exe: ReplaceOptions.Exe = .detect
argv: []const []const u8
stderr_limit: Io.Limit = .unlimited
stdout_limit: Io.Limit = .unlimited
reserve_amount: usize = 64

初始为标准错误及标准输出分配的字节数。

cwd: Child.Cwd = .inherit

设置此项,可在创建子进程时更改当前工作目录。

environ_map: ?*const Environ.Map = null

提供时替换子进程环境。此处的 PATH 值 不用于解析 argv[0];该解析始终使用父进程环境。

expand_arg0: ArgExpansion = .no_expand
progress_node: std.Progress.Node = std.Progress.Node.none

填充此字段时,会为子进程创建管道, 以向父进程报告进度。管道写端的 文件描述符会通过子进程中的 ZIG_PROGRESS 环境变量指定。子进程报告的进度 会附加到父进程的此进度节点。

将此节点替换为子进程根节点, 从而把子进程进度树接入父进程进度树。

create_no_window: bool = true

仅限 Windows。在 CreateProcess 中设置 CREATE_NO_WINDOW 标志。

timeout: Io.Timeout = .none

std.process.RunResult

容器

第 499 行

字段

term: Child.Term
stdout: []u8
stderr: []u8

std.process.setCurrentDir

函数

第 910 行

将当前工作目录改为已打开的目录句柄所指目录。 对应 libc 中的“fchdir”。

这会修改进程全局状态,在多线程应用程序中可能产生意外影响。通常,多数应用程序,尤其是库,不应调用此函数;不过,实现命令解释器或执行子进程等场景可能用得上它。

调用此函数会降低代码的可移植性与可复用性。

pub fn setCurrentDir(io: Io, dir: Io.Dir) !void

参数

io: Io
dir: Io.Dir

std.process.SetCurrentDirError

错误集合

第 889 行

错误

AccessDenied
BadPathName
Canceled Cancelable

调用方请求停止异步操作。

FileNotFound
FileSystem
NameTooLong
NoDevice
NotDir
OperationUnsupported
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume

std.process.setCurrentPath

函数

第 939 行

将当前工作目录改为给定路径。 对应 libc 中的“chdir”。

这会修改进程全局状态,在多线程应用程序中可能产生意外影响。通常,多数应用程序,尤其是库,不应调用此函数;不过,实现命令解释器或执行子进程等场景可能用得上它。

调用此函数会降低代码的可移植性与可复用性。

pub fn setCurrentPath(io: Io, path: []const u8) !void

参数

io: Io
path: []const u8

std.process.SetCurrentPathError

错误集合

第 914 行

错误

AccessDenied
BadPathName
Canceled Cancelable

调用方请求停止异步操作。

FileNotFound
FileSystem
InvalidWtf8

仅限 Windows。路径不是有效的 WTF-8。 https://wtf-8.codeberg.page/

NameTooLong
NoDevice
NotDir
OperationUnsupported
SymLinkLoop
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.process.spawn

函数

第 462 行

创建子进程。

pub fn spawn(io: Io, options: SpawnOptions) SpawnError!Child

参数

io: Io
options: SpawnOptions

错误

AccessDenied OpenError

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy OpenError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileSystem
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

InvalidBatchScriptArg

仅限 Windows。执行 .bat 或 .cmd 脚本时,参数中不允许 NUL(U+0000)、LF(U+000A)和 CR(U+000D)。

  • NUL 与 LF 表示参数结束,其后的内容在执行后会丢失。
  • CR 会被 cmd.exe 移除,因此执行后所有 CR 码点都会丢失。
InvalidExe
InvalidName
InvalidProcessGroupId
InvalidUserId
InvalidWtf8

仅限 Windows。提供的 cwd 或 argv 为无效 WTF-8。 https://wtf-8.codeberg.page/

IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound OpenError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice

仅限 POSIX。选择了 StdIo.ignore,且打开 /dev/null 时返回 ENODEV。

NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

OperationUnsupported

操作系统不支持创建子进程。

OutOfMemory
PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied
PipeBusy OpenError
ProcessAlreadyExec

尝试更改调用进程某个子进程的 进程组 ID,但该子进程已经执行 映像替换。

ProcessFdQuotaExceeded
ReadOnlyFileSystem OpenError
ResourceLimitReached
SymLinkLoop
SystemFdQuotaExceeded
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.process.SpawnError

错误集合

第 342 行

错误

AccessDenied OpenError

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy OpenError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileSystem
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

InvalidBatchScriptArg

仅限 Windows。执行 .bat 或 .cmd 脚本时,参数中不允许 NUL(U+0000)、LF(U+000A)和 CR(U+000D)。

  • NUL 与 LF 表示参数结束,其后的内容在执行后会丢失。
  • CR 会被 cmd.exe 移除,因此执行后所有 CR 码点都会丢失。
InvalidExe
InvalidName
InvalidProcessGroupId
InvalidUserId
InvalidWtf8

仅限 Windows。提供的 cwd 或 argv 为无效 WTF-8。 https://wtf-8.codeberg.page/

IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound OpenError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice

仅限 POSIX。选择了 StdIo.ignore,且打开 /dev/null 时返回 ENODEV。

NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

OperationUnsupported

操作系统不支持创建子进程。

OutOfMemory
PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied
PipeBusy OpenError
ProcessAlreadyExec

尝试更改调用进程某个子进程的 进程组 ID,但该子进程已经执行 映像替换。

ProcessFdQuotaExceeded
ReadOnlyFileSystem OpenError
ResourceLimitReached
SymLinkLoop
SystemFdQuotaExceeded
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnrecognizedVolume

在 Windows 上,卷不包含可识别的文件系统。文件 系统驱动可能未加载,或卷可能已损坏。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.process.SpawnOptions

容器

第 383 行

字段

exe: ReplaceOptions.Exe = .detect
argv: []const []const u8
cwd: Child.Cwd = .inherit

设置此项,可在创建子进程时更改当前工作目录。

environ_map: ?*const Environ.Map = null

提供时替换子进程环境。此处的 PATH 值 不用于解析 argv[0];该解析始终使用父进程环境。

expand_arg0: ArgExpansion = .no_expand
progress_node: std.Progress.Node = .none

填充此字段时,会为子进程创建管道, 以向父进程报告进度。管道写端的 文件描述符会通过子进程中的 ZIG_PROGRESS 环境变量指定。子进程报告的进度 会附加到父进程的此进度节点。

将此节点替换为子进程根节点, 从而把子进程进度树接入父进程进度树。

stdin: StdIo = .inherit
stdout: StdIo = .inherit
stderr: StdIo = .inherit
inherit_dirs: []const Dir = &.{}
inherit_files: []const File = &.{}
request_resource_usage_statistics: bool = false

设为 true,以获取子进程的 rusage 信息。 是否能获得所请求统计信息,取决于目标平台和实现状态。 若可用,则 resource_usage_statistics 字段会在调用 wait 后填充。 在 Linux 和 Darwin 上,通过 wait4() 获取 rusage 统计。

uid: ?posix.uid_t = null

设置此项可在创建子进程时更改用户 ID。

gid: ?posix.gid_t = null

设置此项可在创建子进程时更改组 ID。

pgid: ?posix.pid_t = null

设置后,在派生子进程时更改进程组标识。

start_suspended: bool = false

以挂起状态启动子进程。 在 Posix 系统上,以如同已发送 SIGSTOP 的状态启动。

create_no_window: bool = false

仅限 Windows。在 CreateProcess 中设置 CREATE_NO_WINDOW 标志。

std.process.SpawnOptions.StdIo

容器

第 432 行

子进程的标准输入、标准输出及标准错误流的行为。

字段

inherit

从父进程继承对应的流。

file: File

将父进程中已打开的文件传给子进程。

若设置了非阻塞模式,子进程中会保留该模式,但子进程很可能不支持。例如:

  • Zig 的 std.Io.File.stdout() 假定使用阻塞模式。
  • Rust 明确记载,非阻塞标准输入输出可能导致 panic。
  • C++ 标准流不支持非阻塞文件描述符。
ignore

在 POSIX 上打开 "/dev/null",在 Windows 上打开 "NUL", 以向子进程传入空流。

pipe

为流创建新管道。

对应字段(stdout、stderr 或 stdin)将被 赋为可用于读取或写入管道的 File 对象。

close

创建子进程时不提供对应的流。这 可能导致子进程尝试使用标准输入、标准输出 或标准错误时遇到 EBADF;如果只关闭其中一个流, 则可能使这些流混淆。通常,此选项仅适用于 高级使用场景。

std.process.std

别名

第 4 行

别名目标 std

std.process.test_page

变量

第 1110 行

[std.heap.page_size_max]u8

std.process.testing

别名

第 13 行

别名目标 std.testing

std.process.totalSystemMemory

函数

第 570 行

以 u64 返回系统总内存字节数。 使用 u64 而非 usize,是因为 ARM 上存在 PAE, 且使用 QEMU 用户模式模拟时,Linux 的 /proc/meminfo 可能报告更多内存。

pub fn totalSystemMemory() TotalSystemMemoryError!u64

错误

UnknownTotalSystemMemory

std.process.TotalSystemMemoryError

错误集合

第 562 行

错误

UnknownTotalSystemMemory

std.process.unicode

别名

第 16 行

别名目标 std.unicode

std.process.unlockMemory

函数

第 1004 行

撤回要求进程虚拟地址空间驻留于 RAM 的请求。

对应 libc 的“munlock”。

另见:

pub fn unlockMemory(memory: []align(std.heap.page_size_min) const u8) UnlockMemoryError!void

参数

memory: []align(std.heap.page_size_min) const u8

错误

OutOfMemory
PermissionDenied
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.process.unlockMemoryAll

函数

第 1047 行

pub fn unlockMemoryAll() UnlockMemoryError!void

错误

OutOfMemory
PermissionDenied
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.process.UnlockMemoryError

错误集合

第 992 行

错误

OutOfMemory
PermissionDenied
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.process.UserInfo

容器

第 98 行

字段

uid: posix.uid_t
gid: posix.gid_t

std.process.windows

别名

第 15 行

别名目标 std.os.windows

std.process.WindowsExtension

容器

第 332 行

Windows 上 CreateProcess() 原生支持的文件扩展名。

字段

bat
cmd
com
exe

std.process.WindowsExtension.max_len

常量

第 339 行

最长受支持扩展名的长度(以 ASCII 字符计)

源码

std/process.zig

const builtin = @import("builtin");
const native_os = builtin.os.tag;

const std = @import("std.zig");
const Io = std.Io;
const Dir = std.Io.Dir;
const File = std.Io.File;
const fs = std.fs;
const mem = std.mem;
const math = std.math;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const testing = std.testing;
const posix = std.posix;
const windows = std.os.windows;
const unicode = std.unicode;
const max_path_bytes = std.fs.max_path_bytes;

pub const Child = @import("process/Child.zig");
pub const Args = @import("process/Args.zig");
pub const Environ = @import("process/Environ.zig");
pub const Preopens = @import("process/Preopens.zig");

/// 一组标准的、预先初始化的实用接口,供程序使用。这是 main 函数第一个参数的类型。
/// 需要更高灵活性的应用程序可以改为接受 `Init.Minimal`。
///
/// 完成 https://github.com/ziglang/zig/issues/24510 后,还将允许 main 函数的第二个参数为自定义结构体,其中包含自动解析的命令行参数。
///
///
///
pub const Init = struct {
    /// `Init` 是 `Minimal` 的超集;后者包含在此处。
    minimal: Minimal,
    /// 整个进程存活期间的永久存储,退出时自动
    /// 清理。线程安全。
    arena: *std.heap.ArenaAllocator,
    /// 默认选择的通用分配器,用于临时堆分配。
    /// 调试模式下会在可能时启用内存泄漏检查。
    /// 线程安全。
    gpa: Allocator,
    /// 根据目标配置选择合适的默认 Io 实现。
    /// 调试模式下会尽可能启用泄漏检查。
    io: Io,
    /// 环境变量,使用 `gpa` 初始化。非线程安全。
    environ_map: *Environ.Map,
    /// 父进程提供的具名文件。主要用于 WASI,
    /// 但也可在其他系统上模拟与标准输入输出相关的行为。
    ///
    preopens: Preopens,

    /// 可作为 main 函数首个参数、替代 `Init` 的类型。
    pub const Minimal = struct {
        /// 环境变量。
        environ: Environ,
        /// 命令行参数。
        args: Args,
    };
};

pub const CurrentPathError = error{
    /// 缓冲区过小,无法容纳当前路径。
    NameTooLong,
    /// 在 Windows 上不可能发生。在 WASI 上始终返回。
    CurrentDirUnlinked,
    /// 受底层 libc 或系统调用实现限制,无法获取当前路径。换用更大缓冲区重试也不会成功。
    ///
    ///
    PathExceedsLimit,
} || Io.Cancelable || Io.UnexpectedError;

/// 在 Windows 上,结果以 [WTF-8](https://wtf-8.codeberg.page/) 编码。
/// 在其他平台上,结果是不指定编码的不透明字节序列。
///
pub fn currentPath(io: Io, buffer: []u8) CurrentPathError!usize {
    return io.vtable.processCurrentPath(io.userdata, buffer);
}

pub const CurrentPathAllocError = Allocator.Error || CurrentPathError;

/// 使用大小为 `max_path_bytes` 的缓冲区调用 `currentPath` 的快捷方式。
///
/// Windows 上,结果采用 [WTF-8](https://wtf-8.codeberg.page/) 编码。
/// 其他平台上,结果是不指定
/// 编码的不透明字节序列。
///
/// 调用方拥有返回内存的所有权。
pub fn currentPathAlloc(io: Io, allocator: Allocator) CurrentPathAllocError![:0]u8 {
    var buffer: [max_path_bytes]u8 = undefined;
    const n = try currentPath(io, &buffer);
    return allocator.dupeSentinel(u8, buffer[0..n], 0);
}

test currentPathAlloc {
    const cwd = try currentPathAlloc(testing.io, testing.allocator);
    testing.allocator.free(cwd);
}

pub const UserInfo = struct {
    uid: posix.uid_t,
    gid: posix.gid_t,
};

/// 根据用户名获取 uid 的 POSIX 函数。
pub fn getUserInfo(io: Io, name: []const u8) !UserInfo {
    return switch (native_os) {
        .linux,
        .driverkit,
        .ios,
        .maccatalyst,
        .macos,
        .tvos,
        .visionos,
        .watchos,
        .freebsd,
        .netbsd,
        .openbsd,
        .haiku,
        .illumos,
        .serenity,
        => posixGetUserInfo(io, name),
        else => @compileError("Unsupported OS"),
    };
}

/// TODO: 此处读取 /etc/passwd,但用户/标识映射有时位于 NIS、AD 等其他来源。
/// 参见 `man nss`,或查看 `id myuser` 的 strace。
pub fn posixGetUserInfo(io: Io, name: []const u8) !UserInfo {
    const file = try Io.Dir.openFileAbsolute(io, "/etc/passwd", .{});
    defer file.close(io);
    var buffer: [4096]u8 = undefined;
    var file_reader = file.reader(io, &buffer);
    return posixGetUserInfoPasswdStream(name, &file_reader.interface) catch |err| switch (err) {
        error.ReadFailed => return file_reader.err.?,
        error.EndOfStream => return error.UserNotFound,
        error.CorruptPasswordFile => |e| return e,
    };
}

fn posixGetUserInfoPasswdStream(name: []const u8, reader: *std.Io.Reader) !UserInfo {
    const State = enum {
        start,
        wait_for_next_line,
        skip_password,
        read_user_id,
        read_group_id,
    };

    var name_index: usize = 0;
    var uid: posix.uid_t = 0;
    var gid: posix.gid_t = 0;

    sw: switch (State.start) {
        .start => switch (try reader.takeByte()) {
            ':' => {
                if (name_index == name.len) {
                    continue :sw .skip_password;
                } else {
                    continue :sw .wait_for_next_line;
                }
            },
            '\n' => return error.CorruptPasswordFile,
            else => |byte| {
                if (name_index == name.len or name[name_index] != byte) {
                    continue :sw .wait_for_next_line;
                }
                name_index += 1;
                continue :sw .start;
            },
        },
        .wait_for_next_line => switch (try reader.takeByte()) {
            '\n' => {
                name_index = 0;
                continue :sw .start;
            },
            else => continue :sw .wait_for_next_line,
        },
        .skip_password => switch (try reader.takeByte()) {
            '\n' => return error.CorruptPasswordFile,
            ':' => {
                continue :sw .read_user_id;
            },
            else => continue :sw .skip_password,
        },
        .read_user_id => switch (try reader.takeByte()) {
            ':' => {
                continue :sw .read_group_id;
            },
            '\n' => return error.CorruptPasswordFile,
            else => |byte| {
                const digit = switch (byte) {
                    '0'...'9' => byte - '0',
                    else => return error.CorruptPasswordFile,
                };
                {
                    const ov = @mulWithOverflow(uid, 10);
                    if (ov[1] != 0) return error.CorruptPasswordFile;
                    uid = ov[0];
                }
                {
                    const ov = @addWithOverflow(uid, digit);
                    if (ov[1] != 0) return error.CorruptPasswordFile;
                    uid = ov[0];
                }
                continue :sw .read_user_id;
            },
        },
        .read_group_id => switch (try reader.takeByte()) {
            '\n', ':' => return .{
                .uid = uid,
                .gid = gid,
            },
            else => |byte| {
                const digit = switch (byte) {
                    '0'...'9' => byte - '0',
                    else => return error.CorruptPasswordFile,
                };
                {
                    const ov = @mulWithOverflow(gid, 10);
                    if (ov[1] != 0) return error.CorruptPasswordFile;
                    gid = ov[0];
                }
                {
                    const ov = @addWithOverflow(gid, digit);
                    if (ov[1] != 0) return error.CorruptPasswordFile;
                    gid = ov[0];
                }
                continue :sw .read_group_id;
            },
        },
    }
    comptime unreachable;
}

pub fn getBaseAddress() usize {
    switch (native_os) {
        .linux => {
            const phdrs = std.posix.getSelfPhdrs();
            var base: usize = 0;
            for (phdrs) |phdr| switch (phdr.type) {
                .LOAD => return base + phdr.vaddr,
                .PHDR => base = @intFromPtr(phdrs.ptr) - phdr.vaddr,
                else => {},
            } else unreachable;
        },
        .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
            return @intFromPtr(&std.c._mh_execute_header);
        },
        .windows => return @intFromPtr(windows.peb().ImageBaseAddress),
        else => @compileError("Unsupported OS"),
    }
}

/// 返回目标操作系统是否支持替换当前进程映像。
/// 若为 `false`,则调用 `replace` 或 `replaceFile`
/// 函数将返回 `error.OperationUnsupported`。
pub const can_replace = switch (native_os) {
    .windows, .haiku, .wasi => false,
    else => true,
};

/// 表示是否支持创建子进程。
pub const can_spawn = switch (native_os) {
    .wasi, .ios, .tvos, .visionos, .watchos => false,
    else => true,
};

pub const ReplaceError = error{
    /// 目标操作系统无法用新的进程映像替换当前映像。
    ///
    OperationUnsupported,
    SystemResources,
    AccessDenied,
    PermissionDenied,
    InvalidExe,
    FileSystem,
    IsDir,
    FileNotFound,
    NotDir,
    FileBusy,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
} || Allocator.Error || Io.Dir.PathNameError || Io.Cancelable || Io.UnexpectedError;

pub const ReplaceOptions = struct {
    exe: Exe = .detect,
    argv: []const []const u8,

    /// 设置此项,可在创建子进程时更改当前工作目录。
    cwd: Child.Cwd = .inherit,
    /// 如果提供,则替换环境。此处的 PATH 值
    /// 绝不会用于解析 `argv[0]`。
    environ_map: ?*const Environ.Map = null,
    expand_arg0: ArgExpansion = .no_expand,

    inherit_dirs: []const Dir = &.{},
    inherit_files: []const File = &.{},

    /// 以挂起状态启动子进程。
    /// 在 Posix 系统上,以如同已发送 SIGSTOP 的状态启动。
    start_suspended: bool = false,

    pub const Exe = union(enum) {
        /// `argv[0]` 为要执行的程序名称。若它尚不是
        /// 文件路径(即包含 '/',原文如此),则根据父环境中的
        /// PATH 将其解析为文件路径。
        detect,
        /// `argv[0]` 是待执行程序的名称,根据父进程环境中的 PATH 解析为文件路径。
        ///
        search,
        /// `argv[0]` 是要执行程序的文件路径,相对于 `Dir` 载荷。
        /// 它*始终*被视为文件路径,即使不包含 '/'。
        path: Dir,
        /// `File` 载荷是要执行的程序。
        file: File,
        /// `path` 是要执行程序的文件路径,相对于 `dir`。
        /// 它*始终*被视为文件路径,即使不包含 '/'。
        explicit: struct { dir: Dir, path: []const u8 },
    };
};

/// 以被执行进程替换当前进程映像。若此
/// 函数成功,则不返回。
///
/// 不得在 fork() 的子进程中调用此函数。
pub fn replace(io: Io, options: ReplaceOptions) ReplaceError {
    return io.vtable.processReplace(io.userdata, options);
}

pub const ArgExpansion = enum { expand, no_expand };

/// Windows 上 `CreateProcess()` 原生支持的文件扩展名。
pub const WindowsExtension = enum {
    bat,
    cmd,
    com,
    exe,

    /// 最长受支持扩展名的长度(以 ASCII 字符计)
    pub const max_len = 3;
};

pub const SpawnError = error{
    /// 操作系统不支持创建子进程。
    OperationUnsupported,
    OutOfMemory,
    /// 仅限 POSIX。选择了 `StdIo.ignore`,且打开 `/dev/null` 时返回 ENODEV。
    NoDevice,
    /// 仅限 Windows。提供的 `cwd` 或 `argv` 为无效 WTF-8。
    /// https://wtf-8.codeberg.page/
    InvalidWtf8,
    /// 仅限 Windows。执行 `.bat` 或 `.cmd` 脚本时,参数中不允许 NUL(U+0000)、LF(U+000A)和 CR(U+000D)。
    /// - NUL 与 LF 表示参数结束,其后的内容在执行后会丢失。
    /// - CR 会被 `cmd.exe` 移除,因此执行后所有 CR 码点都会丢失。
    ///
    ///
    ///
    InvalidBatchScriptArg,
    SystemResources,
    AccessDenied,
    PermissionDenied,
    InvalidExe,
    FileSystem,
    IsDir,
    FileNotFound,
    NotDir,
    FileBusy,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    ResourceLimitReached,
    InvalidUserId,
    InvalidProcessGroupId,
    SymLinkLoop,
    InvalidName,
    /// 尝试更改调用进程某个子进程的
    /// 进程组 ID,但该子进程已经执行
    /// 映像替换。
    ProcessAlreadyExec,
    /// 在 Windows 上,卷不包含可识别的文件系统。文件
    /// 系统驱动可能未加载,或卷可能已损坏。
    UnrecognizedVolume,
} || Io.File.OpenError || Io.Dir.PathNameError || Io.Cancelable || Io.UnexpectedError;

pub const SpawnOptions = struct {
    exe: ReplaceOptions.Exe = .detect,
    argv: []const []const u8,

    /// 设置此项,可在创建子进程时更改当前工作目录。
    cwd: Child.Cwd = .inherit,
    /// 提供时替换子进程环境。此处的 PATH 值
    /// 不用于解析 `argv[0]`;该解析始终使用父进程环境。
    ///
    environ_map: ?*const Environ.Map = null,
    expand_arg0: ArgExpansion = .no_expand,
    /// 填充此字段时,会为子进程创建管道,
    /// 以向父进程报告进度。管道写端的
    /// 文件描述符会通过子进程中的 `ZIG_PROGRESS`
    /// 环境变量指定。子进程报告的进度
    /// 会附加到父进程的此进度节点。
    ///
    /// 将此节点替换为子进程根节点,
    /// 从而把子进程进度树接入父进程进度树。
    progress_node: std.Progress.Node = .none,

    stdin: StdIo = .inherit,
    stdout: StdIo = .inherit,
    stderr: StdIo = .inherit,
    inherit_dirs: []const Dir = &.{},
    inherit_files: []const File = &.{},

    /// 设为 true,以获取子进程的 rusage 信息。
    /// 是否能获得所请求统计信息,取决于目标平台和实现状态。
    /// 若可用,则 `resource_usage_statistics` 字段会在调用 `wait` 后填充。
    /// 在 Linux 和 Darwin 上,通过 wait4() 获取 rusage 统计。
    ///
    ///
    request_resource_usage_statistics: bool = false,

    /// 设置此项可在创建子进程时更改用户 ID。
    uid: ?posix.uid_t = null,
    /// 设置此项可在创建子进程时更改组 ID。
    gid: ?posix.gid_t = null,
    /// 设置后,在派生子进程时更改进程组标识。
    pgid: ?posix.pid_t = null,

    /// 以挂起状态启动子进程。
    /// 在 Posix 系统上,以如同已发送 SIGSTOP 的状态启动。
    start_suspended: bool = false,
    /// 仅限 Windows。在 CreateProcess 中设置 CREATE_NO_WINDOW 标志。
    create_no_window: bool = false,

    /// 子进程的标准输入、标准输出及标准错误流的行为。
    pub const StdIo = union(enum) {
        /// 从父进程继承对应的流。
        inherit,
        /// 将父进程中已打开的文件传给子进程。
        ///
        /// 若设置了非阻塞模式,子进程中会保留该模式,但子进程很可能不支持。例如:
        /// - Zig 的 std.Io.File.stdout() 假定使用阻塞模式。
        /// - Rust 明确记载,非阻塞标准输入输出可能导致 panic。
        /// - C++ 标准流不支持非阻塞文件描述符。
        ///
        file: File,
        /// 在 POSIX 上打开 "/dev/null",在 Windows 上打开 "NUL",
        /// 以向子进程传入空流。
        ignore,
        /// 为流创建新管道。
        ///
        /// 对应字段(`stdout`、`stderr` 或 `stdin`)将被
        /// 赋为可用于读取或写入管道的
        /// `File` 对象。
        pipe,
        /// 创建子进程时不提供对应的流。这
        /// 可能导致子进程尝试使用标准输入、标准输出
        /// 或标准错误时遇到 EBADF;如果只关闭其中一个流,
        /// 则可能使这些流混淆。通常,此选项仅适用于
        /// 高级使用场景。
        close,
    };
};

/// 创建子进程。
pub fn spawn(io: Io, options: SpawnOptions) SpawnError!Child {
    return io.vtable.processSpawn(io.userdata, options);
}

pub const RunError = error{
    StreamTooLong,
} || SpawnError || Io.File.MultiReader.UnendingError || Io.Timeout.Error;

pub const RunOptions = struct {
    exe: ReplaceOptions.Exe = .detect,
    argv: []const []const u8,
    stderr_limit: Io.Limit = .unlimited,
    stdout_limit: Io.Limit = .unlimited,
    /// 初始为标准错误及标准输出分配的字节数。
    reserve_amount: usize = 64,

    /// 设置此项,可在创建子进程时更改当前工作目录。
    cwd: Child.Cwd = .inherit,
    /// 提供时替换子进程环境。此处的 PATH 值
    /// 不用于解析 `argv[0]`;该解析始终使用父进程环境。
    ///
    environ_map: ?*const Environ.Map = null,
    expand_arg0: ArgExpansion = .no_expand,
    /// 填充此字段时,会为子进程创建管道,
    /// 以向父进程报告进度。管道写端的
    /// 文件描述符会通过子进程中的 `ZIG_PROGRESS`
    /// 环境变量指定。子进程报告的进度
    /// 会附加到父进程的此进度节点。
    ///
    /// 将此节点替换为子进程根节点,
    /// 从而把子进程进度树接入父进程进度树。
    progress_node: std.Progress.Node = std.Progress.Node.none,
    /// 仅限 Windows。在 CreateProcess 中设置 CREATE_NO_WINDOW 标志。
    create_no_window: bool = true,
    timeout: Io.Timeout = .none,
};

pub const RunResult = struct {
    term: Child.Term,
    stdout: []u8,
    stderr: []u8,
};

/// 生成子进程,等待其退出并收集 stdout、stderr,然后返回。
/// 成功时,调用方拥有 result.stdout 和 result.stderr 内存的所有权。
pub fn run(gpa: Allocator, io: Io, options: RunOptions) RunError!RunResult {
    var child = try spawn(io, .{
        .exe = options.exe,
        .argv = options.argv,
        .cwd = options.cwd,
        .environ_map = options.environ_map,
        .expand_arg0 = options.expand_arg0,
        .progress_node = options.progress_node,
        .create_no_window = options.create_no_window,

        .stdin = .ignore,
        .stdout = .pipe,
        .stderr = .pipe,
    });
    defer child.kill(io);

    var multi_reader_buffer: Io.File.MultiReader.Buffer(2) = undefined;
    var multi_reader: Io.File.MultiReader = undefined;
    multi_reader.init(gpa, io, multi_reader_buffer.toStreams(), &.{ child.stdout.?, child.stderr.? });
    defer multi_reader.deinit();

    const stdout_reader = multi_reader.reader(0);
    const stderr_reader = multi_reader.reader(1);

    while (multi_reader.fill(options.reserve_amount, options.timeout)) |_| {
        if (options.stdout_limit.toInt()) |limit| {
            if (stdout_reader.buffered().len > limit)
                return error.StreamTooLong;
        }
        if (options.stderr_limit.toInt()) |limit| {
            if (stderr_reader.buffered().len > limit)
                return error.StreamTooLong;
        }
    } else |err| switch (err) {
        error.EndOfStream => {},
        else => |e| return e,
    }

    try multi_reader.checkAnyError();

    const term = try child.wait(io);

    const stdout_slice = try multi_reader.toOwnedSlice(0);
    errdefer gpa.free(stdout_slice);

    const stderr_slice = try multi_reader.toOwnedSlice(1);
    errdefer gpa.free(stderr_slice);

    return .{
        .stdout = stdout_slice,
        .stderr = stderr_slice,
        .term = term,
    };
}

pub const TotalSystemMemoryError = error{
    UnknownTotalSystemMemory,
};

/// 以 u64 返回系统总内存字节数。
/// 使用 u64 而非 usize,是因为 ARM 上存在 PAE,
/// 且使用 QEMU 用户模式模拟时,Linux 的 /proc/meminfo
/// 可能报告更多内存。
pub fn totalSystemMemory() TotalSystemMemoryError!u64 {
    switch (native_os) {
        .linux => {
            var info: std.os.linux.Sysinfo = undefined;
            const result: usize = std.os.linux.sysinfo(&info);
            if (std.os.linux.errno(result) != .SUCCESS) {
                return error.UnknownTotalSystemMemory;
            }
            // 提升为 u64,以避免在 info.totalram 为 32 位 usize 的系统上溢出
            return @as(u64, info.totalram) * info.mem_unit;
        },
        .dragonfly, .freebsd, .netbsd => {
            const name = if (native_os == .netbsd) "hw.physmem64" else "hw.physmem";
            var physmem: c_ulong = undefined;
            var len: usize = @sizeOf(c_ulong);
            switch (posix.errno(posix.system.sysctlbyname(name, &physmem, &len, null, 0))) {
                .SUCCESS => return @intCast(physmem),
                .FAULT => unreachable,
                .PERM => unreachable, // 仅在设置值时
                .NOMEM => unreachable, // 内存已位于栈上
                .NOENT => unreachable,
                else => return error.UnknownTotalSystemMemory,
            }
        },
        // 整个 Darwin 系列
        .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
            // "hw.memsize" 返回 uint64_t
            var physmem: u64 = undefined;
            var len: usize = @sizeOf(u64);
            switch (posix.errno(posix.system.sysctlbyname("hw.memsize", &physmem, &len, null, 0))) {
                .SUCCESS => return physmem,
                .FAULT => unreachable,
                .PERM => unreachable, // 仅在设置值时
                .NOMEM => unreachable, // 内存已位于栈上
                .NOENT => unreachable, // 常量,已知有效的值
                else => return error.UnknownTotalSystemMemory,
            }
        },
        .openbsd => {
            const mib: [2]c_int = [_]c_int{
                posix.CTL.HW,
                posix.HW.PHYSMEM64,
            };
            var physmem: i64 = undefined;
            var len: usize = @sizeOf(@TypeOf(physmem));
            posix.sysctl(&mib, &physmem, &len, null, 0) catch |err| switch (err) {
                error.NameTooLong => unreachable, // 常量,已知有效的值
                error.PermissionDenied => unreachable, // 仅在设置值时,
                error.SystemResources => unreachable, // 内存已位于栈上
                error.UnknownName => unreachable, // 常量,已知有效的值
                else => return error.UnknownTotalSystemMemory,
            };
            assert(physmem >= 0);
            return @as(u64, @bitCast(physmem));
        },
        .windows => {
            var sbi: windows.SYSTEM.BASIC_INFORMATION = undefined;
            const rc = windows.ntdll.NtQuerySystemInformation(
                .Basic,
                &sbi,
                @sizeOf(windows.SYSTEM.BASIC_INFORMATION),
                null,
            );
            if (rc != .SUCCESS) {
                return error.UnknownTotalSystemMemory;
            }
            return @as(u64, sbi.NumberOfPhysicalPages) * sbi.PageSize;
        },
        else => return error.UnknownTotalSystemMemory,
    }
}

/// 表明将以成功退出码终止的意图。
///
/// 在调试构建中不执行任何操作,以便测试调用代码的清理
/// 机制,同时使外部工具能够准确检查资源
/// 泄漏。在发布构建中,以零退出码调用 `exit`,
/// 不再返回。
pub fn cleanExit(io: Io) void {
    if (builtin.mode == .debug) return;
    _ = io.lockStderr(&.{}, .no_color) catch {};
    exit(0);
}

/// 请求允许同时打开更多文件描述符。
///
/// 在某些系统上,这会在出现 ProcessFdQuotaExceeded
/// 错误之前提高限制。在其他系统上,不执行任何操作。
pub fn raiseFileDescriptorLimit() void {
    const have_rlimit = posix.rlimit_resource != void;
    if (!have_rlimit) return;

    var lim = posix.getrlimit(.NOFILE) catch return; // 尝试未成功。
    if (native_os.isDarwin()) {
        // 在 Darwin 上,`NOFILE` 受硬编码值 `OPEN_MAX` 限制。
        // 根据 setrlimit() 的手册:
        //   setrlimit() 现在会在过去能够成功的情况下返回,并将 errno 设为 EINVAL。
        //   对于 RLIM.NOFILE,不再接受“rlim_cur = RLIM.INFINITY”。
        //   应使用“rlim_cur = min(OPEN_MAX, rlim_max)”。
        lim.max = @min(std.c.OPEN_MAX, lim.max);
    }
    if (lim.cur == lim.max) return;

    // 通过二分搜索查找界限。
    var min: posix.rlim_t = lim.cur;
    var max: posix.rlim_t = 1 << 20;
    // 但若存在已定义的上界,则不搜索,直接设置。
    if (lim.max != posix.RLIM.INFINITY) {
        min = lim.max;
        max = lim.max;
    }

    while (true) {
        lim.cur = min + @divTrunc(max - min, 2); // 在 FreeBSD 上,rlim_t 为有符号类型
        if (posix.setrlimit(.NOFILE, lim)) |_| {
            min = lim.cur;
        } else |_| {
            max = lim.cur;
        }
        if (min + 1 >= max) break;
    }
}

test raiseFileDescriptorLimit {
    raiseFileDescriptorLimit();
}

/// 记录错误,然后以退出码 1 终止进程。
pub fn fatal(comptime format: []const u8, format_arguments: anytype) noreturn {
    std.log.err(format, format_arguments);
    exit(1);
}

pub const ExecutablePathBaseError = error{
    FileNotFound,
    AccessDenied,
    /// 操作系统不支持可执行文件获取自身
    /// 路径。
    OperationUnsupported,
    NotDir,
    SymLinkLoop,
    InputOutput,
    FileTooBig,
    IsDir,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    NoDevice,
    SystemResources,
    NoSpaceLeft,
    FileSystem,
    BadPathName,
    DeviceBusy,
    PipeBusy,
    NotLink,
    PathAlreadyExists,
    /// 在 Windows 上,未找到 `\\server` 或 `\\server\share`。
    NetworkNotFound,
    ProcessNotFound,
    /// Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。
    /// 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
    ///
    ///
    ///
    AntivirusInterference,
    /// 在 Windows 上,卷不包含可识别的文件系统。文件
    /// 系统驱动可能未加载,或卷可能已损坏。
    UnrecognizedVolume,
    PermissionDenied,
} || Io.Cancelable || Io.UnexpectedError;

pub const ExecutablePathAllocError = ExecutablePathBaseError || Allocator.Error;

pub fn executablePathAlloc(io: Io, allocator: Allocator) ExecutablePathAllocError![:0]u8 {
    var buffer: [max_path_bytes]u8 = undefined;
    const n = executablePath(io, &buffer) catch |err| switch (err) {
        error.NameTooLong => unreachable,
        else => |e| return e,
    };
    return allocator.dupeSentinel(u8, buffer[0..n], 0);
}

pub const ExecutablePathError = ExecutablePathBaseError || error{NameTooLong};

/// 获取当前可执行文件的路径,并解析符号链接。
///
/// 若当前可执行文件在进程启动后
/// 被删除,此函数可能返回错误。
///
/// 返回值是 out_buffer 的切片。
///
/// Windows 上,结果采用 [WTF-8](https://wtf-8.codeberg.page/) 编码。
/// 其他平台上,结果是不指定编码的不透明字节序列。
///
/// Linux 上依赖已挂载的 procfs。若当前执行的二进制文件
/// 已被删除,文件路径类似于 "/a/b/c/exe (deleted)"。
///
/// 另请参见:
/// * `executableDirPath`:仅获取目录。
/// * `openExecutable`:仅获取已打开的文件句柄。
pub fn executablePath(io: Io, out_buffer: []u8) ExecutablePathError!usize {
    return io.vtable.processExecutablePath(io.userdata, out_buffer);
}

/// 获取包含当前可执行文件的目录路径。
///
/// 返回 `out_buffer` 中的索引。
///
/// 在 Windows 上,结果以 [WTF-8](https://wtf-8.codeberg.page/) 编码。
/// 在其他平台上,结果是不指定编码的不透明字节序列。
pub fn executableDirPath(io: Io, out_buffer: []u8) ExecutablePathError!usize {
    const n = try executablePath(io, out_buffer);
    // 断言操作系统 API 返回绝对路径,因此 dirname 不会返回 null。
    //
    return std.fs.path.dirname(out_buffer[0..n]).?.len;
}

/// 与 `executableDirPath` 相同,但会为结果分配内存。
pub fn executableDirPathAlloc(io: Io, allocator: Allocator) ExecutablePathAllocError![]u8 {
    var buffer: [max_path_bytes]u8 = undefined;
    const dir_path_len = executableDirPath(io, &buffer) catch |err| switch (err) {
        error.NameTooLong => unreachable,
        else => |e| return e,
    };
    return allocator.dupe(u8, buffer[0..dir_path_len]);
}

pub const OpenExecutableError = File.OpenError || ExecutablePathError || File.LockError;

pub fn openExecutable(io: Io, flags: Dir.OpenFileOptions) OpenExecutableError!File {
    return io.vtable.processExecutableOpen(io.userdata, flags);
}

/// 导致进程异常终止。
///
/// 若链接 libc,则调用 `std.c.abort`。否则先发送
/// SIGABRT,再发送 SIGKILL。
///
/// 若当前存在 SIGABRT 信号处理程序,则调用它。
pub fn abort() noreturn {
    @branchHint(.cold);
    // MSVCRT 的 abort() 有时会打开不希望出现的弹窗,
    // 因此即使在 Windows 上链接 libc,也使用自己的 abort 实现。
    // 更多信息见 https://github.com/ziglang/zig/issues/2071 。
    if (native_os == .windows) {
        if (builtin.mode == .debug and windows.peb().BeingDebugged.toBool()) {
            @breakpoint();
        }
        windows.ntdll.RtlExitUserProcess(3);
    }
    if (!builtin.link_libc and native_os == .linux) {
        // Linux 手册页称,libc 的 abort() 函数
        // “首先解除对 SIGABRT 信号的阻塞”,但对用户自定义信号处理器
        // 而言,这存在隐患:处理器可能希望在某些程序区域恢复状态,
        // 在另一些区域崩溃。
        // 因此,如果存在用户安装的 SIGABRT 处理器,则运行它。
        posix.raise(.ABRT) catch {};

        // 禁用所有信号处理函数。
        const filledset = std.os.linux.sigfillset();
        posix.sigprocmask(posix.SIG.BLOCK, &filledset, null);

        // 仅允许一个线程继续执行 abort() 的其余部分。
        if (!builtin.single_threaded) {
            const global = struct {
                var abort_entered: bool = false;
            };
            while (@cmpxchgWeak(bool, &global.abort_entered, false, true, .seq_cst, .seq_cst)) |_| {}
        }

        // 安装默认处理器,使下面的 tkill 能终止进程。
        const sigact: posix.Sigaction = .{
            .handler = .{ .handler = posix.SIG.DFL },
            .mask = posix.sigemptyset(),
            .flags = 0,
        };
        posix.sigaction(.ABRT, &sigact, null);

        _ = std.os.linux.tkill(std.os.linux.gettid(), .ABRT);

        var sigabrtmask = posix.sigemptyset();
        posix.sigaddset(&sigabrtmask, .ABRT);
        posix.sigprocmask(posix.SIG.UNBLOCK, &sigabrtmask, null);

        // 此位置之后应当不可达。
        @as(*allowzero volatile u8, @ptrFromInt(0)).* = 0;
        posix.raise(.KILL) catch {};
        exit(127); // 某些容器中可能无法向 PID 1 发送信号。
    }
    switch (native_os) {
        .uefi, .wasi, .emscripten, .cuda, .amdhsa, .other, .freestanding => @trap(),
        else => posix.system.abort(),
    }
}

/// 以指定状态码退出程序的全部线程。
pub fn exit(status: u8) noreturn {
    if (builtin.link_libc) {
        std.c.exit(status);
    } else switch (native_os) {
        .windows => windows.ntdll.RtlExitUserProcess(status),
        .wasi => std.os.wasi.proc_exit(status),
        .linux => {
            if (!builtin.single_threaded) std.os.linux.exit_group(status);
            posix.system.exit(status);
        },
        .uefi => {
            const uefi = std.os.uefi;
            // 仅在尚未调用 exitBootServices() 时才能使用 exit()。
            // 此 exit 调用不应失败,因此捕获并忽略错误。
            if (uefi.system_table.boot_services) |bs| {
                bs.exit(uefi.handle, @fromBackingInt(@intCast(status)), null) catch {};
            }
            // 如果无法退出,则改为重启系统。
            uefi.system_table.runtime_services.resetSystem(.cold, @fromBackingInt(@intCast(status)), null);
        },
        else => posix.system.exit(status),
    }
}

pub const SetCurrentDirError = error{
    AccessDenied,
    BadPathName,
    FileNotFound,
    FileSystem,
    NameTooLong,
    NoDevice,
    NotDir,
    OperationUnsupported,
    UnrecognizedVolume,
} || Io.Cancelable || Io.UnexpectedError;

/// 将当前工作目录改为已打开的目录句柄所指目录。
/// 对应 libc 中的“fchdir”。
///
/// 这会修改进程全局状态,在多线程应用程序中可能产生意外影响。通常,多数应用程序,尤其是库,不应调用此函数;不过,实现命令解释器或执行子进程等场景可能用得上它。
///
/// 调用此函数会降低代码的可移植性与可复用性。
///
///
///
pub fn setCurrentDir(io: Io, dir: Io.Dir) !void {
    return io.vtable.processSetCurrentDir(io.userdata, dir);
}

pub const SetCurrentPathError = error{
    AccessDenied,
    SymLinkLoop,
    SystemResources,
    BadPathName,
    FileNotFound,
    FileSystem,
    NoDevice,
    NotDir,
    NameTooLong,
    OperationUnsupported,
    /// 仅限 Windows。路径不是有效的 WTF-8。
    /// https://wtf-8.codeberg.page/
    InvalidWtf8,
} || Io.Cancelable || Io.UnexpectedError;

/// 将当前工作目录改为给定路径。
/// 对应 libc 中的“chdir”。
///
/// 这会修改进程全局状态,在多线程应用程序中可能产生意外影响。通常,多数应用程序,尤其是库,不应调用此函数;不过,实现命令解释器或执行子进程等场景可能用得上它。
///
/// 调用此函数会降低代码的可移植性与可复用性。
///
///
///
pub fn setCurrentPath(io: Io, path: []const u8) !void {
    return io.vtable.processSetCurrentPath(io.userdata, path);
}

pub const LockMemoryError = error{
    UnsupportedOperation,
    PermissionDenied,
    LockedMemoryLimitExceeded,
    SystemResources,
} || Io.UnexpectedError;

pub const LockMemoryOptions = struct {
    /// 锁定当前驻留页面,并标记整个范围,
    /// 以便剩余非驻留页面因缺页而填充时
    /// 也被锁定。
    on_fault: bool = false,
};

/// 请求将调用进程的一部分虚拟地址空间保留在 RAM 中,
/// 防止该内存被换出到交换区。
///
/// 对应 libc 中的 "mlock" 或 "mlock2"。
///
/// 另见:
/// * unlockMemory
pub fn lockMemory(memory: []align(std.heap.page_size_min) const u8, options: LockMemoryOptions) LockMemoryError!void {
    if (native_os == .windows) {
        // TODO: 调用 VirtualLock
    }
    if (!options.on_fault and @TypeOf(posix.system.mlock) != void) {
        switch (posix.errno(posix.system.mlock(memory.ptr, memory.len))) {
            .SUCCESS => return,
            .INVAL => |err| return std.Io.Threaded.errnoBug(err), // 未对齐、为负数,或超出地址空间末尾。
            .PERM => return error.PermissionDenied,
            .NOMEM => return error.LockedMemoryLimitExceeded,
            .AGAIN => return error.SystemResources,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
    if (@TypeOf(posix.system.mlock2) != void) {
        const flags: posix.MLOCK = .{ .ONFAULT = options.on_fault };
        switch (posix.errno(posix.system.mlock2(memory.ptr, memory.len, flags))) {
            .SUCCESS => return,
            .INVAL => |err| return std.Io.Threaded.errnoBug(err), // 未对齐、为负数,或超出地址空间末尾。
            .PERM => return error.PermissionDenied,
            .NOMEM => return error.LockedMemoryLimitExceeded,
            .AGAIN => return error.SystemResources,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
    return error.UnsupportedOperation;
}

pub const UnlockMemoryError = error{
    PermissionDenied,
    OutOfMemory,
    SystemResources,
} || Io.UnexpectedError;

/// 撤回要求进程虚拟地址空间驻留于 RAM 的请求。
///
/// 对应 libc 的“munlock”。
///
/// 另见:
/// * `lockMemory`
pub fn unlockMemory(memory: []align(std.heap.page_size_min) const u8) UnlockMemoryError!void {
    if (@TypeOf(posix.system.munlock) == void) return;
    switch (posix.errno(posix.system.munlock(memory.ptr, memory.len))) {
        .SUCCESS => return,
        .INVAL => |err| return std.Io.Threaded.errnoBug(err), // 未对齐,或超出地址空间末尾
        .PERM => return error.PermissionDenied,
        .NOMEM => return error.OutOfMemory,
        .AGAIN => return error.SystemResources,
        else => |err| return posix.unexpectedErrno(err),
    }
}

pub const LockMemoryAllOptions = struct {
    current: bool = false,
    future: bool = false,
    /// 断言与 `current` 或 `future` 至少一项一起使用。
    on_fault: bool = false,
};

pub fn lockMemoryAll(options: LockMemoryAllOptions) LockMemoryError!void {
    if (@TypeOf(posix.system.mlockall) == void) return error.UnsupportedOperation;
    var flags: posix.MCL = .{
        .CURRENT = options.current,
        .FUTURE = options.future,
    };
    if (options.on_fault) {
        assert(options.current or options.future);
        if (@hasField(posix.MCL, "ONFAULT")) {
            flags.ONFAULT = true;
        } else {
            return error.UnsupportedOperation;
        }
    }
    switch (posix.errno(posix.system.mlockall(flags))) {
        .SUCCESS => return,
        .INVAL => |err| return std.Io.Threaded.errnoBug(err),
        .PERM => return error.PermissionDenied,
        .NOMEM => return error.LockedMemoryLimitExceeded,
        .AGAIN => return error.SystemResources,
        else => |err| return posix.unexpectedErrno(err),
    }
}

pub fn unlockMemoryAll() UnlockMemoryError!void {
    if (@TypeOf(posix.system.munlockall) == void) return;
    switch (posix.errno(posix.system.munlockall())) {
        .SUCCESS => return,
        .PERM => return error.PermissionDenied,
        .NOMEM => return error.OutOfMemory,
        .AGAIN => return error.SystemResources,
        else => |err| return posix.unexpectedErrno(err),
    }
}

pub const ProtectMemoryError = error{
    UnsupportedOperation,
    /// 若指定区域包含此前通过 `mimmutable` 函数
    /// 标记为不可变的任何页面,OpenBSD 将拒绝
    /// 更改其内存保护。
    PermissionDenied,
    /// 无法授予此内存指定的访问权限。例如,
    /// 将只有只读访问权限的文件映射到内存后,
    /// 再用 `protectMemory` 将其标记为可写,就可能出现此情况。
    AccessDenied,
    /// 更改某个内存区域的保护属性将导致
    /// 具有不同属性的映射总数超过允许的
    /// 最大值。
    OutOfMemory,
} || Io.UnexpectedError;

pub const MemoryProtection = packed struct(u3) {
    read: bool = false,
    write: bool = false,
    execute: bool = false,
};

pub fn protectMemory(memory: []align(std.heap.page_size_min) u8, protection: MemoryProtection) ProtectMemoryError!void {
    if (native_os == .windows) {
        var addr = memory.ptr; // 此处 ntdll 需要额外一级间接访问
        var size = memory.len; // 此处 ntdll 需要额外一级间接访问
        var old: windows.PAGE = undefined;
        const current_process: windows.HANDLE = @ptrFromInt(@as(usize, @bitCast(@as(isize, -1))));
        const new = windows.PAGE.fromProtection(protection) orelse return error.AccessDenied;
        switch (windows.ntdll.NtProtectVirtualMemory(current_process, @ptrCast(&addr), &size, new, &old)) {
            .SUCCESS => return,
            .INVALID_ADDRESS => return error.AccessDenied,
            else => |st| return windows.unexpectedStatus(st),
        }
    } else if (posix.PROT != void) {
        const flags: posix.PROT = .{
            .READ = protection.read,
            .WRITE = protection.write,
            .EXEC = protection.execute,
        };
        switch (posix.errno(posix.system.mprotect(memory.ptr, memory.len, flags))) {
            .SUCCESS => return,
            .PERM => return error.PermissionDenied,
            .INVAL => |err| return std.Io.Threaded.errnoBug(err),
            .ACCES => return error.AccessDenied,
            .NOMEM => return error.OutOfMemory,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
    return error.UnsupportedOperation;
}

var test_page: [std.heap.page_size_max]u8 align(std.heap.page_size_max) = undefined;

test lockMemory {
    lockMemory(&test_page, .{}) catch return error.SkipZigTest;
    unlockMemory(&test_page) catch return error.SkipZigTest;
}

test lockMemoryAll {
    lockMemoryAll(.{ .current = true }) catch return error.SkipZigTest;
    unlockMemoryAll() catch return error.SkipZigTest;
}

test protectMemory {
    protectMemory(&test_page, .{}) catch return error.SkipZigTest;
    protectMemory(&test_page, .{ .read = true, .write = true }) catch return error.SkipZigTest;
}

test {
    _ = Child;
    _ = Args;
    _ = Environ;
    _ = Preopens;
}