POSIX API 层。
比直接使用操作系统专用 API 更跨平台,但与 std.Io 和
std.process 等其他命名空间相比,
层次更低,可移植性更弱。
当且仅当链接 libc 时,这些 API 通常会降低为 libc 函数调用。Windows、Linux 和 WASI 之外的多数操作系统 总是要求链接 libc,因为它们将 libc 作为稳定的系统调用 ABI。
builtinnative_osstdIomemmaxIntcastassertpage_size_minuse_libclinuxwindowswasisystemAFAF_SUNAIARCHATAT_SUNCLOCKCPU_COUNTCTLDTEElf_SymndxFFD_CLOEXECFlockHOST_NAME_MAXHWIFNAMESIZEIOV_MAXIPIPV6IPPROTOIPTOSKERNKeventMADVMAPMAX_ADDR_LENMCLMFDMLOCKMREMAPMSFMSGNAME_MAXNSIGOPATH_MAXPOLLPOSIX_FADVPRPROTRLIMSSASCSCMSEEKSHUTSIGSIOCGIFINDEXSOSOCKSOLIFFSTDERR_FILENOSTDIN_FILENOSTDOUT_FILENOSYSSigactionStatTTCPVDSOW_SCaddrinfoblkcnt_tblksize_tclock_tclockid_tcmsghdrcmsg_aligntimerfd_clockid_tcpu_set_tdev_tdl_phdr_infofd_tfile_objgid_tifreqin_pktinfoin6_pktinfoino_tlingermode_tmsghdrmsghdr_constnfds_tnlink_toff_tpid_tpollfdport_eventport_notifyport_trlim_trlimitrlimit_resourcerusagesa_family_tsiginfo_tsigset_tsigrtminsigrtmaxsockaddrsocklen_tstack_ttime_ttimespectimestamp_ttimevaltimezoneUTIMEuid_tuser_descutsnametermiosCSIZENCCScc_tVspeed_ttc_iflag_ttc_oflag_ttc_cflag_ttc_lflag_tF_OKR_OKW_OKX_OKioveciovec_constACCMODETCSAwinsizeLOCKLOGsocket_terrnoRebootErrorRebootCommandrebootRaiseErrorraiseKillErrorkillReadErrorreadOpenErroropenatopenatZgetppidGetSockNameErrorgetpeernameFanotifyInitErrorfanotify_initFanotifyMarkErrorfanotify_markfanotify_markZMMapErrormmapmunmapMRemapErrormremapMSyncErrormsyncSysCtlErrorsysctlgetSelfPhdrsdl_iterate_phdrSchedGetAffinityErrorsched_getaffinitySigaltstackErrorsigaltstacksigfillsetsigemptysetsigaddsetsigdelsetsigismembersigactionsigprocmaskGetHostNameErrorgethostnameunamePollErrorpollPPollErrorppollSetSockOptErrorsetsockoptMemFdCreateErrormemfd_createZmemfd_creategetrusageTIOCErrorTermiosGetErrortcgetattrTermiosSetErrortcsetattrTermioGetPgrpErrortcgetpgrpTermioSetPgrpErrortcsetpgrpsignalfdSyncErrorsyncsyncfsfdatasyncPrctlErrorprctlGetrlimitErrorgetrlimitSetrlimitErrorsetrlimitMincoreErrormincoreMadviseErrormadvisePerfEventOpenErrorperf_event_openPtraceErrorptraceNameToFileHandleAtErrorname_to_handle_atname_to_handle_atZlfs64_abiUnexpectedErrorunexpectedErrnotoPosixPath
std.posix._SC
常量
std.posix.ACCMODE
类型
std.posix.addrinfo
常量
std.posix.AF
常量
std.posix.AF_SUN
常量
std.posix.AI
常量
std.posix.ARCH
常量
std.posix.assert
别名
别名目标 std.debug.assert
std.posix.AT
常量
std.posix.AT_SUN
常量
std.posix.blkcnt_t
常量
std.posix.blksize_t
常量
std.posix.builtin
常量
std.posix.cast
别名
别名目标 std.math.cast
std.posix.cc_t
常量
std.posix.CLOCK
常量
std.posix.clock_t
常量
std.posix.clockid_t
常量
std.posix.cmsg_align
常量
std.posix.cmsghdr
常量
std.posix.CPU_COUNT
常量
std.posix.cpu_set_t
常量
std.posix.CSIZE
常量
std.posix.CTL
常量
std.posix.dev_t
常量
std.posix.dl_iterate_phdr
函数
pub fn dl_iterate_phdr( context: anytype, comptime Error: type, comptime callback: fn (info: *dl_phdr_info, size: usize, context: @TypeOf(context)) Error!void, ) Error!void
参数
Error: type
callback: fn (info: *dl_phdr_info, size: usize, context: @TypeOf(context)) Error!void
std.posix.dl_iterate_phdr.callbackC
函数
fn callbackC(info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.c) c_int
参数
std.posix.dl_phdr_info
常量
std.posix.DT
常量
std.posix.E
常量
std.posix.Elf_Symndx
常量
std.posix.errno
常量
从系统函数调用的返回值取得 errno。
某些系统上直接从系统调用返回值取得该值; 其他系统上则使用线程局部 errno 变量。因此, 只有紧接在希望观察 errno 的系统函数调用 之后调用,此函数的返回值才是定义明确的。
std.posix.F
常量
std.posix.F_OK
常量
std.posix.fanotify_init
函数
pub fn fanotify_init(flags: std.os.linux.fanotify.InitFlags, event_f_flags: u32) FanotifyInitError!i32
参数
错误
- PermissionDenied
- ProcessFdQuotaExceeded
- SystemFdQuotaExceeded
- SystemResources
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UnsupportedFlags
内核无法识别传入的标志, 可能因为内核版本较旧。
std.posix.fanotify_mark
函数
pub fn fanotify_mark( fanotify_fd: fd_t, flags: std.os.linux.fanotify.MarkFlags, mask: std.os.linux.fanotify.MarkMask, dirfd: fd_t, pathname: ?[]const u8, ) FanotifyMarkError!void
参数
fanotify_fd: fd_t
flags: std.os.linux.fanotify.MarkFlags
mask: std.os.linux.fanotify.MarkMask
dirfd: fd_t
pathname: ?[]const u8
错误
- CrossDevice
- FileNotFound
- IsDir
- MarkAlreadyExists
- NameTooLong
- NotAssociatedWithFileSystem
- NotDir
- OperationUnsupported
- PermissionDenied
- SystemResources
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UserMarkQuotaExceeded
std.posix.fanotify_markZ
函数
pub fn fanotify_markZ( fanotify_fd: fd_t, flags: std.os.linux.fanotify.MarkFlags, mask: std.os.linux.fanotify.MarkMask, dirfd: fd_t, pathname: ?[*:0]const u8, ) FanotifyMarkError!void
参数
fanotify_fd: fd_t
flags: std.os.linux.fanotify.MarkFlags
mask: std.os.linux.fanotify.MarkMask
dirfd: fd_t
pathname: ?[*:0]const u8
错误
- CrossDevice
- FileNotFound
- IsDir
- MarkAlreadyExists
- NameTooLong
- NotAssociatedWithFileSystem
- NotDir
- OperationUnsupported
- PermissionDenied
- SystemResources
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UserMarkQuotaExceeded
std.posix.FanotifyInitError
错误集合
错误
- PermissionDenied
- ProcessFdQuotaExceeded
- SystemFdQuotaExceeded
- SystemResources
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UnsupportedFlags
内核无法识别传入的标志, 可能因为内核版本较旧。
std.posix.FanotifyMarkError
错误集合
错误
- CrossDevice
- FileNotFound
- IsDir
- MarkAlreadyExists
- NameTooLong
- NotAssociatedWithFileSystem
- NotDir
- OperationUnsupported
- PermissionDenied
- SystemResources
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UserMarkQuotaExceeded
std.posix.FD_CLOEXEC
常量
std.posix.fd_t
常量
std.posix.fdatasync
函数
将指定文件描述符的全部待写文件内容写入底层文件系统,但不一定写入元数据。
pub fn fdatasync(fd: fd_t) SyncError!void
参数
fd: fd_t
错误
- AccessDenied SyncError
- Canceled Cancelable
调用方请求停止异步操作。
- DiskQuota SyncError
- InputOutput SyncError
- NoSpaceLeft SyncError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.file_obj
常量
std.posix.Flock
常量
std.posix.gethostname
函数
pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8
参数
name_buffer: *[HOST_NAME_MAX]u8
错误
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.GetHostNameError
错误集合
错误
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.getpeername
函数
pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSockNameError!void
参数
错误
- FileDescriptorNotASocket
- NetworkDown
网络子系统已失败。
- SocketNotBound
套接字尚未绑定
- SocketUnconnected
套接字未连接(仅适用于面向连接的套接字)。
- SystemResources
系统可用资源不足,无法执行操作。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.getppid
函数
pub fn getppid() pid_t
std.posix.getrlimit
函数
pub fn getrlimit(resource: rlimit_resource) GetrlimitError!rlimit
参数
resource: rlimit_resource
错误
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.GetrlimitError
别名
std.posix.getrusage
函数
pub fn getrusage(who: i32) rusage
参数
who: i32
std.posix.getSelfPhdrs
函数
pub fn getSelfPhdrs() []std.elf.ElfN.Phdr
std.posix.GetSockNameError
错误集合
错误
- FileDescriptorNotASocket
- NetworkDown
网络子系统已失败。
- SocketNotBound
套接字尚未绑定
- SocketUnconnected
套接字未连接(仅适用于面向连接的套接字)。
- SystemResources
系统可用资源不足,无法执行操作。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.gid_t
常量
std.posix.HOST_NAME_MAX
常量
std.posix.HW
常量
std.posix.IFF
常量
std.posix.IFNAMESIZE
常量
std.posix.ifreq
常量
std.posix.in_pktinfo
常量
std.posix.in6_pktinfo
常量
std.posix.ino_t
常量
std.posix.Io
别名
别名目标 std.Io
std.posix.IOV_MAX
常量
std.posix.iovec
容器
字段
base: [*]u8
len: usize
std.posix.iovec_const
容器
字段
base: [*]const u8
len: usize
std.posix.IP
常量
std.posix.IPPROTO
常量
std.posix.IPTOS
常量
std.posix.IPV6
常量
std.posix.KERN
常量
std.posix.Kevent
常量
std.posix.kill
函数
pub fn kill(pid: pid_t, sig: SIG) KillError!void
参数
错误
- PermissionDenied
- ProcessNotFound
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.KillError
错误集合
错误
- PermissionDenied
- ProcessNotFound
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.lfs64_abi
常量
std.posix.linger
常量
std.posix.linux
别名
别名目标 std.os.linux
std.posix.LOCK
命名空间
std.posix.LOCK.EX
常量
std.posix.LOCK.NB
常量
std.posix.LOCK.SH
常量
std.posix.LOCK.UN
常量
std.posix.LOG
命名空间
std.posix.LOG.ALERT
常量
必须立即采取操作
std.posix.LOG.CRIT
常量
严重情况
std.posix.LOG.DEBUG
常量
调试级别消息
std.posix.LOG.EMERG
常量
系统不可用
std.posix.LOG.ERR
常量
错误条件
std.posix.LOG.INFO
常量
信息性
std.posix.LOG.NOTICE
常量
正常但值得注意的情况
std.posix.LOG.WARNING
常量
警告条件
std.posix.MADV
常量
std.posix.madvise
函数
提供内存使用建议。 此系统调用可选,有时配置为禁用。
pub fn madvise(ptr: [*]align(page_size_min) u8, length: usize, advice: u32) MadviseError!void
参数
错误
- AccessDenied
advice 为 MADV.REMOVE,但指定地址范围不是共享可写映射。
- InvalidSyscall
以下情况之一:
- addr 未按页对齐,或 length 为负数
- advice 无效
- advice 为 MADV.DONTNEED 或 MADV.REMOVE,且指定地址范围 包含锁定页、Huge TLB 页或 VM_PFNMAP 页
- advice 为 MADV.MERGEABLE 或 MADV.UNMERGEABLE,但内核未 配置 CONFIG_KSM
- advice 为 MADV.FREE 或 MADV.WIPEONFORK,但指定地址范围 包含文件、Huge TLB、MAP.SHARED 或 VM_PFNMAP 范围
- MadviseUnavailable
此 Linux 内核版本及配置不支持 madvise 系统调用。
- OutOfMemory
以下情况之一:
- (对于 MADV.WILLNEED)内存不足:换入失败。
- 指定范围内的地址当前未映射,或 位于进程地址空间之外。
- PermissionDenied
advice 为 MADV.HWPOISON,但调用方没有 CAP_SYS_ADMIN 能力。
- SystemResources
某内核资源暂时不可用。
- Unexpected
操作系统返回了未记录的错误码。
- WouldExceedMaximumResidentSetSize
(用于 MADV.WILLNEED)将此区域调入内存会超过进程的 最大驻留集大小。
std.posix.MadviseError
错误集合
错误
- AccessDenied
advice 为 MADV.REMOVE,但指定地址范围不是共享可写映射。
- InvalidSyscall
以下情况之一:
- addr 未按页对齐,或 length 为负数
- advice 无效
- advice 为 MADV.DONTNEED 或 MADV.REMOVE,且指定地址范围 包含锁定页、Huge TLB 页或 VM_PFNMAP 页
- advice 为 MADV.MERGEABLE 或 MADV.UNMERGEABLE,但内核未 配置 CONFIG_KSM
- advice 为 MADV.FREE 或 MADV.WIPEONFORK,但指定地址范围 包含文件、Huge TLB、MAP.SHARED 或 VM_PFNMAP 范围
- MadviseUnavailable
此 Linux 内核版本及配置不支持 madvise 系统调用。
- OutOfMemory
以下情况之一:
- (对于 MADV.WILLNEED)内存不足:换入失败。
- 指定范围内的地址当前未映射,或 位于进程地址空间之外。
- PermissionDenied
advice 为 MADV.HWPOISON,但调用方没有 CAP_SYS_ADMIN 能力。
- SystemResources
某内核资源暂时不可用。
- Unexpected
操作系统返回了未记录的错误码。
- WouldExceedMaximumResidentSetSize
(用于 MADV.WILLNEED)将此区域调入内存会超过进程的 最大驻留集大小。
std.posix.MAP
常量
std.posix.MAX_ADDR_LEN
常量
std.posix.maxInt
别名
别名目标 std.math.maxInt
std.posix.MCL
常量
std.posix.mem
别名
别名目标 std.mem
std.posix.memfd_create
函数
pub fn memfd_create(name: []const u8, flags: u32) MemFdCreateError!fd_t
参数
name: []const u8
flags: u32
错误
- NameTooLong
提供的名称超过
NAME_MAX,或传入了无效标志。- OutOfMemory
- ProcessFdQuotaExceeded
- SystemFdQuotaExceeded
- SystemOutdated
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.memfd_createZ
函数
pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t
参数
name: [*:0]const u8
flags: u32
错误
- NameTooLong
提供的名称超过
NAME_MAX,或传入了无效标志。- OutOfMemory
- ProcessFdQuotaExceeded
- SystemFdQuotaExceeded
- SystemOutdated
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.MemFdCreateError
错误集合
错误
- NameTooLong
提供的名称超过
NAME_MAX,或传入了无效标志。- OutOfMemory
- ProcessFdQuotaExceeded
- SystemFdQuotaExceeded
- SystemOutdated
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.MFD
常量
std.posix.mincore
函数
确定页面是否驻留在内存中。
pub fn mincore(ptr: [*]align(page_size_min) u8, length: usize, vec: [*]u8) MincoreError!void
参数
错误
- InvalidAddress
vec 指向无效地址。
- InvalidSyscall
addr 未按页对齐。
- MincoreUnavailable
此类 UNIX 内核的当前版本及配置 不提供 mincore 系统调用。
- OutOfMemory
以下任一情况:
- length 大于用户空间 TASK_SIZE - addr
- addr + length 包含未映射内存
- SystemResources
某内核资源暂时不可用。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.MincoreError
错误集合
错误
- InvalidAddress
vec 指向无效地址。
- InvalidSyscall
addr 未按页对齐。
- MincoreUnavailable
此类 UNIX 内核的当前版本及配置 不提供 mincore 系统调用。
- OutOfMemory
以下任一情况:
- length 大于用户空间 TASK_SIZE - addr
- addr + length 包含未映射内存
- SystemResources
某内核资源暂时不可用。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.MLOCK
常量
std.posix.mmap
函数
将文件或设备映射到内存。
length 无需对齐。
使用映射区域可能产生以下信号:
- SIGSEGV:尝试写入只读映射区域。
- SIGBUS:尝试访问缓冲区中不对应文件的部分。
pub fn mmap( ptr: ?[*]align(page_size_min) u8, length: usize, prot: PROT, flags: MAP, fd: fd_t, offset: u64, ) MMapError![]align(page_size_min) u8
参数
错误
- AccessDenied
文件描述符引用非普通文件;或请求文件映射, 但文件描述符未以读取方式打开;或请求
MAP.SHARED并设置PROT_WRITE,但文件描述符未以RDWR模式打开; 或设置PROT_WRITE,但文件仅允许追加。- LockedMemoryLimitExceeded
- MappingAlreadyExists
使用 FIXED_NOREPLACE 标志,但进程已在给定地址映射内存。
- MemoryMappingNotSupported
指定文件的底层文件系统不支持内存映射。
- OutOfMemory
- PermissionDenied
prot参数请求PROT_EXEC,但映射区域属于 挂载为禁止执行的文件系统中的文件。- ProcessFdQuotaExceeded
- SystemFdQuotaExceeded
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.MMapError
错误集合
错误
- AccessDenied
文件描述符引用非普通文件;或请求文件映射, 但文件描述符未以读取方式打开;或请求
MAP.SHARED并设置PROT_WRITE,但文件描述符未以RDWR模式打开; 或设置PROT_WRITE,但文件仅允许追加。- LockedMemoryLimitExceeded
- MappingAlreadyExists
使用 FIXED_NOREPLACE 标志,但进程已在给定地址映射内存。
- MemoryMappingNotSupported
指定文件的底层文件系统不支持内存映射。
- OutOfMemory
- PermissionDenied
prot参数请求PROT_EXEC,但映射区域属于 挂载为禁止执行的文件系统中的文件。- ProcessFdQuotaExceeded
- SystemFdQuotaExceeded
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.mode_t
常量
std.posix.mremap
函数
pub fn mremap( old_address: ?[*]align(page_size_min) u8, old_len: usize, new_len: usize, flags: system.MREMAP, new_address: ?[*]align(page_size_min) u8, ) MRemapError![]align(page_size_min) u8
参数
old_address: ?[*]align(page_size_min) u8
old_len: usize
new_len: usize
flags: system.MREMAP
new_address: ?[*]align(page_size_min) u8
错误
- InvalidSyscallParameters
要么是调用代码存在缺陷, 要么是操作系统滥用了 EINVAL 错误码。
- LockedMemoryLimitExceeded
- OutOfMemory
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.MREMAP
常量
std.posix.MRemapError
错误集合
错误
- InvalidSyscallParameters
要么是调用代码存在缺陷, 要么是操作系统滥用了 EINVAL 错误码。
- LockedMemoryLimitExceeded
- OutOfMemory
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.MSF
常量
std.posix.MSG
常量
std.posix.msghdr
常量
std.posix.msghdr_const
常量
std.posix.msync
函数
pub fn msync(memory: []align(page_size_min) u8, flags: i32) MSyncError!void
参数
memory: []align(page_size_min) u8
flags: i32
错误
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UnmappedMemory
std.posix.MSyncError
错误集合
错误
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UnmappedMemory
std.posix.munmap
函数
删除指定地址范围的映射,使之后对 该范围内地址的引用成为无效内存引用。 注意,虽然 POSIX 允许解除已有映射中间一段区域的映射, Zig 的 munmap 函数却不允许,原因有二:
- 这违反了 Zig 要求资源释放必须成功的原则。
- Windows 的 NtFreeVirtualMemory 函数有此限制。
pub fn munmap(memory: []align(page_size_min) const u8) void
参数
memory: []align(page_size_min) const u8
std.posix.NAME_MAX
常量
std.posix.name_to_handle_at
函数
pub fn name_to_handle_at( dirfd: fd_t, pathname: []const u8, handle: *std.os.linux.file_handle, mount_id: *i32, flags: u32, ) NameToFileHandleAtError!void
参数
错误
- FileNotFound
- NameTooLong
- NotDir
- OperationUnsupported
- Unexpected
std.posix.name_to_handle_atZ
函数
pub fn name_to_handle_atZ( dirfd: fd_t, pathname_z: [*:0]const u8, handle: *std.os.linux.file_handle, mount_id: *i32, flags: u32, ) NameToFileHandleAtError!void
参数
错误
- FileNotFound
- NameTooLong
- NotDir
- OperationUnsupported
- Unexpected
std.posix.NameToFileHandleAtError
错误集合
错误
- FileNotFound
- NameTooLong
- NotDir
- OperationUnsupported
- Unexpected
std.posix.native_os
常量
std.posix.NCCS
常量
std.posix.nfds_t
常量
std.posix.nlink_t
常量
std.posix.NSIG
常量
std.posix.O
常量
std.posix.off_t
常量
std.posix.openat
函数
打开文件,必要时创建文件。若被中断则不断重试。
file_path 相对于已打开的目录句柄 dir_fd。
Windows 上,file_path 应编码为 WTF-8。
WASI 上,file_path 应编码为有效 UTF-8。
其他平台上,file_path 是不规定编码的不透明字节序列。
另请参见 openatZ。
pub fn openat(dir_fd: fd_t, file_path: []const u8, flags: O, mode: mode_t) OpenError!fd_t
参数
错误
- 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,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied OpenError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- WouldBlock OpenError
已请求非阻塞模式,但该操作无法立即返回。
std.posix.openatZ
函数
打开文件,并可能创建文件。若被中断,则继续重试。
file_path 相对于已打开的目录句柄 dir_fd。
Windows 上,file_path 应采用 WTF-8 编码。
WASI 上,file_path 应采用有效 UTF-8 编码。
其他平台上,file_path 是不透明的字节序列,没有特定编码。
另见 openat。
pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: O, mode: mode_t) OpenError!fd_t
参数
错误
- 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,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied OpenError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- WouldBlock OpenError
已请求非阻塞模式,但该操作无法立即返回。
std.posix.OpenError
错误集合
错误
- 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,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied OpenError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- WouldBlock OpenError
已请求非阻塞模式,但该操作无法立即返回。
std.posix.page_size_min
别名
std.posix.PATH_MAX
常量
std.posix.perf_event_open
函数
pub fn perf_event_open( attr: *system.perf_event_attr, pid: pid_t, cpu: i32, group_fd: fd_t, flags: usize, ) PerfEventOpenError!fd_t
参数
错误
- DeviceBusy
如果其他事件已独占访问 PMU, 则返回此错误。
- EventNotSupported
请求需要特定硬件特性的事件, 但硬件不支持时返回。包括 请求不受支持的低偏移事件、不可用的分支跟踪、 在没有 PMU 中断时请求采样, 以及为软件事件请求分支栈。
- EventRequiresUnsupportedCpuFeature
- PermissionDenied
请求的事件需要 CAP_SYS_ADMIN 权限 或更宽松的 perf_event paranoid 设置时返回。无特权 进程可能遇到此错误的常见情况 包括:附加到其他用户拥有的进程; 监控给定 CPU 上的所有进程,即将 pid 参数设为 -1;以及在 paranoid 设置 要求时未设置 exclude_kernel。 此外: 在许多架构(并非全部)上,指定不受支持的 exclude_hv、exclude_idle、exclude_user 或 exclude_kernel 设置时也会返回。 与 EACCES 类似,请求事件需要 CAP_SYS_ADMIN 权限或更宽松的 perf_event paranoid 设置时也可能发生。包括 在内核地址上设置断点,以及从 Linux 3.13 开始 设置内核函数跟踪的跟踪点。
- ProcessNotFound
尝试附加到不存在的进程时返回。
- ProcessResources
每个已打开事件使用一个文件描述符。若打开 大量事件,便会达到每进程打开文件描述符 数量的限制,此后将无法再创建 更多事件。
- SampleMaxStackOverflow
请求 PERF_SAMPLE_CALLCHAIN 且 sample_max_stack 大于 /proc/sys/kernel/perf_event_max_stack 中指定的 最大值时返回。
- SampleStackNotSupported
当 sample_type 中设置了 PERF_SAMPLE_STACK_USER, 但硬件不支持时返回。
- TooBig
perf_event_attr 的 size 值过小,小于 PERF_ATTR_SIZE_VER0;过大,大于页大小;或超过内核支持的大小且额外字节不为零时,返回此错误。 返回 E2BIG 时,内核会将 perf_event_attr 的 size 字段覆盖为其期望的结构体大小。
- TooManyBreakpoints
尝试添加的断点事件数 超过硬件支持数量时返回。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.PerfEventOpenError
错误集合
错误
- DeviceBusy
如果其他事件已独占访问 PMU, 则返回此错误。
- EventNotSupported
请求需要特定硬件特性的事件, 但硬件不支持时返回。包括 请求不受支持的低偏移事件、不可用的分支跟踪、 在没有 PMU 中断时请求采样, 以及为软件事件请求分支栈。
- EventRequiresUnsupportedCpuFeature
- PermissionDenied
请求的事件需要 CAP_SYS_ADMIN 权限 或更宽松的 perf_event paranoid 设置时返回。无特权 进程可能遇到此错误的常见情况 包括:附加到其他用户拥有的进程; 监控给定 CPU 上的所有进程,即将 pid 参数设为 -1;以及在 paranoid 设置 要求时未设置 exclude_kernel。 此外: 在许多架构(并非全部)上,指定不受支持的 exclude_hv、exclude_idle、exclude_user 或 exclude_kernel 设置时也会返回。 与 EACCES 类似,请求事件需要 CAP_SYS_ADMIN 权限或更宽松的 perf_event paranoid 设置时也可能发生。包括 在内核地址上设置断点,以及从 Linux 3.13 开始 设置内核函数跟踪的跟踪点。
- ProcessNotFound
尝试附加到不存在的进程时返回。
- ProcessResources
每个已打开事件使用一个文件描述符。若打开 大量事件,便会达到每进程打开文件描述符 数量的限制,此后将无法再创建 更多事件。
- SampleMaxStackOverflow
请求 PERF_SAMPLE_CALLCHAIN 且 sample_max_stack 大于 /proc/sys/kernel/perf_event_max_stack 中指定的 最大值时返回。
- SampleStackNotSupported
当 sample_type 中设置了 PERF_SAMPLE_STACK_USER, 但硬件不支持时返回。
- TooBig
perf_event_attr 的 size 值过小,小于 PERF_ATTR_SIZE_VER0;过大,大于页大小;或超过内核支持的大小且额外字节不为零时,返回此错误。 返回 E2BIG 时,内核会将 perf_event_attr 的 size 字段覆盖为其期望的结构体大小。
- TooManyBreakpoints
尝试添加的断点事件数 超过硬件支持数量时返回。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.pid_t
常量
std.posix.poll
函数
pub fn poll(fds: []pollfd, timeout: i32) PollError!usize
参数
fds: []pollfd
timeout: i32
错误
- NetworkDown
网络子系统已失败。
- SystemResources
内核没有空间分配文件描述符表。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.POLL
常量
std.posix.PollError
错误集合
错误
- NetworkDown
网络子系统已失败。
- SystemResources
内核没有空间分配文件描述符表。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.pollfd
常量
std.posix.port_event
常量
std.posix.port_notify
常量
std.posix.port_t
常量
std.posix.POSIX_FADV
常量
std.posix.ppoll
函数
pub fn ppoll(fds: []pollfd, timeout: ?*const timespec, mask: ?*const sigset_t) PPollError!usize
参数
错误
- SignalInterrupt
操作在完成前被递送的信号中断。
- SystemResources
内核没有空间分配文件描述符表。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.PPollError
错误集合
错误
- SignalInterrupt
操作在完成前被递送的信号中断。
- SystemResources
内核没有空间分配文件描述符表。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.PR
常量
std.posix.prctl
函数
pub fn prctl(option: PR, args: anytype) PrctlError!u31
参数
option: PR
错误
- AccessDenied
仅可能发生于 PR_SET_SECCOMP/SECCOMP_MODE_FILTER 或 PR_SET_MM/PR_SET_MM_EXE_FILE
- InvalidAddress
- InvalidFileDescriptor
仅可与 PR_SET_MM/PR_SET_MM_EXE_FILE 一起出现
- OperationUnsupported
仅可能随 PR_SET_FP_MODE 出现
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UnsupportedFeature
仅可能发生于 PR_SET_SPECULATION_CTRL、PR_MPX_ENABLE_MANAGEMENT 或 PR_MPX_DISABLE_MANAGEMENT
std.posix.PrctlError
错误集合
错误
- AccessDenied
仅可能发生于 PR_SET_SECCOMP/SECCOMP_MODE_FILTER 或 PR_SET_MM/PR_SET_MM_EXE_FILE
- InvalidAddress
- InvalidFileDescriptor
仅可与 PR_SET_MM/PR_SET_MM_EXE_FILE 一起出现
- OperationUnsupported
仅可能随 PR_SET_FP_MODE 出现
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UnsupportedFeature
仅可能发生于 PR_SET_SPECULATION_CTRL、PR_MPX_ENABLE_MANAGEMENT 或 PR_MPX_DISABLE_MANAGEMENT
std.posix.PROT
常量
std.posix.ptrace
函数
pub fn ptrace(request: u32, pid: pid_t, addr: usize, data: usize) PtraceError!void
参数
错误
- DeadLock
- DeviceBusy
- InputOutput
- NameTooLong
- OperationUnsupported
- OutOfMemory
- PermissionDenied
- ProcessNotFound
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.PtraceError
错误集合
错误
- DeadLock
- DeviceBusy
- InputOutput
- NameTooLong
- OperationUnsupported
- OutOfMemory
- PermissionDenied
- ProcessNotFound
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.R_OK
常量
std.posix.raise
函数
pub fn raise(sig: SIG) RaiseError!void
参数
sig: SIG
错误
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.RaiseError
别名
std.posix.read
函数
返回读取的字节数,可能少于
buf.len。读取 0 字节表示文件结束。
如果 fd 以非阻塞模式打开,收到 EAGAIN 时
此函数返回 error.WouldBlock。
Linux 限制单次 read 可传输的字节数,在 64 位和 32 位
系统上均为 0x7ffff000。这是因为返回值使用有符号 C int,
且最后 4096 个值用于存放 errno 错误码。read 手册页说明了这一点。
Darwin 的上限为 0x7fffffff,尝试读取更多字节会返回 EINVAL。
相应的 POSIX 上限是 maxInt(isize)。
pub fn read(fd: fd_t, buf: []u8) ReadError!usize
参数
fd: fd_t
buf: []u8
错误
- AccessDenied UnendingError
在 WASI 中,当文件描述符不具有读取 所需的权限时发生此错误。
- Canceled Cancelable
调用方请求停止异步操作。
- ConnectionResetByPeer UnendingError
- InputOutput UnendingError
- IsDir UnendingError
尝试将目录文件描述符当作普通文件读取。
- LockViolation UnendingError
由于锁定而无法读取文件。根据
Io实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。- NotOpenForReading UnendingError
打开文件时未授予读取能力。
- SocketUnconnected UnendingError
- SystemResources UnendingError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- WouldBlock UnendingError
已启用非阻塞模式,且从该文件描述符读取会阻塞。
std.posix.ReadError
别名
std.posix.reboot
函数
pub fn reboot(cmd: RebootCommand) RebootError!void
参数
cmd: RebootCommand
错误
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.RebootCommand
类型
std.posix.RebootError
错误集合
错误
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.RLIM
常量
std.posix.rlim_t
常量
std.posix.rlimit
常量
std.posix.rlimit_resource
常量
std.posix.rusage
常量
std.posix.S
常量
std.posix.SA
常量
std.posix.sa_family_t
常量
std.posix.SC
常量
std.posix.sched_getaffinity
函数
pub fn sched_getaffinity(pid: pid_t) SchedGetAffinityError!cpu_set_t
参数
pid: pid_t
错误
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.SchedGetAffinityError
错误集合
错误
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.SCM
常量
std.posix.SEEK
常量
std.posix.setrlimit
函数
pub fn setrlimit(resource: rlimit_resource, limits: rlimit) SetrlimitError!void
参数
resource: rlimit_resource
limits: rlimit
错误
- LimitTooBig
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.SetrlimitError
错误集合
错误
- LimitTooBig
- PermissionDenied
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.setsockopt
函数
设置套接字选项。
pub fn setsockopt(fd: socket_t, level: i32, optname: u32, opt: []const u8) SetSockOptError!void
参数
错误
- AlreadyConnected
套接字已连接,而指定选项无法在套接字连接期间设置。
- FileDescriptorNotASocket
- InvalidProtocolOption
协议不支持该选项。
- NetworkDown
- NoDevice
- OperationUnsupported
- PermissionDenied
设置该套接字选项需要更高权限。
- SocketNotBound
- SystemResources
系统可用资源不足,无法完成此调用。
- TimeoutTooBig
发送和接收超时值过大,无法容纳于套接字结构的超时字段中。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.SetSockOptError
错误集合
错误
- AlreadyConnected
套接字已连接,而指定选项无法在套接字连接期间设置。
- FileDescriptorNotASocket
- InvalidProtocolOption
协议不支持该选项。
- NetworkDown
- NoDevice
- OperationUnsupported
- PermissionDenied
设置该套接字选项需要更高权限。
- SocketNotBound
- SystemResources
系统可用资源不足,无法完成此调用。
- TimeoutTooBig
发送和接收超时值过大,无法容纳于套接字结构的超时字段中。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.SHUT
常量
std.posix.SIG
常量
std.posix.sigaction
函数
检查并更改信号处理动作。
pub fn sigaction(sig: SIG, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) void
参数
std.posix.Sigaction
常量
std.posix.sigaddset
函数
pub fn sigaddset(set: *sigset_t, sig: SIG) void
参数
std.posix.sigaltstack
函数
pub fn sigaltstack(ss: ?*const stack_t, old_ss: ?*stack_t) SigaltstackError!void
参数
错误
- PermissionDenied
尝试更改正在使用的信号栈。
- SizeTooSmall
提供的栈大小小于 MINSIGSTKSZ。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.SigaltstackError
错误集合
错误
- PermissionDenied
尝试更改正在使用的信号栈。
- SizeTooSmall
提供的栈大小小于 MINSIGSTKSZ。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.sigdelset
函数
pub fn sigdelset(set: *sigset_t, sig: SIG) void
参数
std.posix.sigemptyset
函数
返回空的 sigset_t。
pub fn sigemptyset() sigset_t
std.posix.sigfillset
函数
返回各位均已设置的 sigset_t。
pub fn sigfillset() sigset_t
std.posix.siginfo_t
常量
std.posix.sigismember
函数
pub fn sigismember(set: *const sigset_t, sig: SIG) bool
参数
std.posix.signalfd
函数
pub fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) !fd_t
参数
std.posix.sigprocmask
函数
设置线程信号掩码。
pub fn sigprocmask(flags: u32, noalias set: ?*const sigset_t, noalias oldset: ?*sigset_t) void
参数
std.posix.sigrtmax
常量
std.posix.sigrtmin
常量
std.posix.sigset_t
常量
std.posix.SIOCGIFINDEX
常量
std.posix.SO
常量
std.posix.SOCK
常量
std.posix.sockaddr
常量
std.posix.socket_t
别名
别名目标 std.posix.fd_t
std.posix.socklen_t
常量
std.posix.SOL
常量
std.posix.speed_t
常量
std.posix.stack_t
常量
std.posix.Stat
类型
Windows 没有 stat 的概念。
Linux 上已移除 stat 的位定义和包装函数,因为需要维护
各目标和 libc 的不同 stat 结构体,易导致运行时
错误。面向 Linux 的用户应添加编译期检查并使用 statx,
类似于 Io.File.stat 的做法。
std.posix.std
别名
别名目标 std
std.posix.STDERR_FILENO
常量
std.posix.STDIN_FILENO
常量
std.posix.STDOUT_FILENO
常量
std.posix.sync
函数
将所有待写入的文件内容及元数据修改写入全部文件系统。
pub fn sync() void
std.posix.SyncError
别名
std.posix.syncfs
函数
将全部待写文件内容和元数据修改写入指定文件所在的文件系统。
pub fn syncfs(fd: fd_t) SyncError!void
参数
fd: fd_t
错误
- AccessDenied SyncError
- Canceled Cancelable
调用方请求停止异步操作。
- DiskQuota SyncError
- InputOutput SyncError
- NoSpaceLeft SyncError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.SYS
常量
std.posix.sysctl
函数
pub fn sysctl( name: []const c_int, oldp: ?*anyopaque, oldlenp: ?*usize, newp: ?*anyopaque, newlen: usize, ) SysCtlError!void
参数
name: []const c_int
oldp: ?*anyopaque
oldlenp: ?*usize
newp: ?*anyopaque
newlen: usize
错误
- NameTooLong
- PermissionDenied
- SystemResources
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UnknownName
std.posix.SysCtlError
错误集合
错误
- NameTooLong
- PermissionDenied
- SystemResources
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- UnknownName
std.posix.system
类型
与 libc 兼容的 API 层。
std.posix.system.blksize_t
类型
std.posix.system.blksize_t
类型
std.posix.system.cmsg_align
常量
std.posix.system.cmsg_align
常量
std.posix.system.cmsghdr
类型
std.posix.system.cmsghdr
类型
std.posix.system.fd_t
类型
std.posix.system.fd_t
类型
std.posix.system.gid_t
类型
std.posix.system.gid_t
类型
std.posix.system.IFNAMESIZE
常量
std.posix.system.IFNAMESIZE
常量
std.posix.system.ino_t
类型
std.posix.system.ino_t
类型
std.posix.system.mode_t
类型
std.posix.system.mode_t
类型
std.posix.system.NAME_MAX
常量
std.posix.system.nlink_t
类型
std.posix.system.nlink_t
类型
std.posix.system.pid_t
类型
std.posix.system.pid_t
类型
std.posix.system.pollfd
类型
std.posix.system.pollfd
类型
std.posix.system.SIG
类型
std.posix.system.SIG
类型
std.posix.system.uid_t
类型
std.posix.system.uid_t
类型
std.posix.T
常量
std.posix.tc_cflag_t
常量
std.posix.tc_iflag_t
常量
std.posix.tc_lflag_t
常量
std.posix.tc_oflag_t
常量
std.posix.tcgetattr
函数
pub fn tcgetattr(handle: fd_t) TermiosGetError!termios
参数
handle: fd_t
错误
- NotATerminal TIOCError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.tcgetpgrp
函数
返回与给定句柄关联的 TTY 的进程组 ID。
pub fn tcgetpgrp(handle: fd_t) TermioGetPgrpError!pid_t
参数
handle: fd_t
错误
- NotATerminal TIOCError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.TCP
常量
std.posix.TCSA
容器
字段
NOW
DRAIN
FLUSH
_
std.posix.tcsetattr
函数
pub fn tcsetattr(handle: fd_t, optional_action: TCSA, termios_p: termios) TermiosSetError!void
参数
错误
- NotATerminal TIOCError
- ProcessOrphaned
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.tcsetpgrp
函数
设置给定 TTY 的控制进程组 ID。 handle 必须是与调用进程关联的 TTY 的有效 fd_t。 pgrp 必须为有效进程组,且调用进程必须是该组成员。
pub fn tcsetpgrp(handle: fd_t, pgrp: pid_t) TermioSetPgrpError!void
参数
错误
- NotAPgrpMember
- NotATerminal TIOCError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.TermioGetPgrpError
错误集合
错误
- NotATerminal TIOCError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.termios
常量
std.posix.TermioSetPgrpError
错误集合
错误
- NotAPgrpMember
- NotATerminal TIOCError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.TermiosGetError
错误集合
错误
- NotATerminal TIOCError
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.TermiosSetError
错误集合
错误
- NotATerminal TIOCError
- ProcessOrphaned
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
std.posix.time_t
常量
std.posix.timerfd_clockid_t
常量
std.posix.timespec
常量
std.posix.timestamp_t
常量
std.posix.timeval
常量
std.posix.timezone
常量
std.posix.TIOCError
错误集合
错误
- NotATerminal
std.posix.toPosixPath
函数
用于在栈上将切片转换为以空字符结尾的切片。
pub fn toPosixPath(file_path: []const u8) error{NameTooLong}![PATH_MAX - 1:0]u8
参数
file_path: []const u8
错误
- NameTooLong
std.posix.uid_t
常量
std.posix.uname
函数
pub fn uname() utsname
std.posix.unexpectedErrno
函数
执行系统调用或其他会设置 errno 的操作后, 遇到意外错误时调用此函数。
pub fn unexpectedErrno(err: E) UnexpectedError
参数
err: E
std.posix.UnexpectedError
别名
std.posix.use_libc
常量
是否为 POSIX API 层使用 libc。
std.posix.user_desc
常量
std.posix.UTIME
常量
std.posix.utsname
常量
std.posix.V
常量
std.posix.VDSO
常量
std.posix.W
常量
std.posix.W_OK
常量
std.posix.wasi
别名
别名目标 std.os.wasi
std.posix.windows
别名
别名目标 std.os.windows
std.posix.winsize
容器
字段
row: u16
col: u16
xpixel: u16
ypixel: u16
std.posix.X_OK
常量
源码
std/posix.zig
//! POSIX API 层。
//!
//! 比直接使用操作系统专用 API 更跨平台,但与 `std.Io` 和
//! `std.process` 等其他命名空间相比,
//! 层次更低,可移植性更弱。
//!
//! 当且仅当链接 libc 时,这些 API 通常会降低为 libc
//! 函数调用。Windows、Linux 和 WASI 之外的多数操作系统
//! 总是要求链接 libc,因为它们将 libc 作为稳定的系统调用 ABI。
const builtin = @import("builtin");
const native_os = builtin.os.tag;
const std = @import("std.zig");
const Io = std.Io;
const mem = std.mem;
const maxInt = std.math.maxInt;
const cast = std.math.cast;
const assert = std.debug.assert;
const page_size_min = std.heap.page_size_min;
test {
_ = @import("posix/test.zig");
}
/// 是否为 POSIX API 层使用 libc。
const use_libc = builtin.link_libc or switch (native_os) {
.windows, .wasi => true,
else => false,
};
const linux = std.os.linux;
const windows = std.os.windows;
const wasi = std.os.wasi;
/// 与 libc 兼容的 API 层。
pub const system = if (use_libc)
std.c
else switch (native_os) {
.linux => linux,
.plan9 => std.os.plan9,
.psp => struct {
pub const fd_t = i32;
pub const pid_t = void;
pub const pollfd = void;
pub const uid_t = void;
pub const gid_t = void;
pub const mode_t = u32;
pub const nlink_t = u32;
pub const blksize_t = u32;
pub const ino_t = u64;
pub const IFNAMESIZE = {};
pub const SIG = void;
pub const cmsghdr = void;
pub const cmsg_align = {};
// https://github.com/pspdev/newlib/blob/9e0a073634ad73e8e088f2e071c55a9fe5d39709/newlib/libc/sys/psp/sys/dirent.h#L19
pub const NAME_MAX = 255;
},
else => struct {
pub const pid_t = void;
pub const pollfd = void;
pub const fd_t = void;
pub const uid_t = void;
pub const gid_t = void;
pub const mode_t = u0;
pub const nlink_t = u0;
pub const blksize_t = void;
pub const ino_t = void;
pub const IFNAMESIZE = {};
pub const SIG = void;
pub const cmsghdr = void;
pub const cmsg_align = {};
},
};
pub const AF = system.AF;
pub const AF_SUN = system.AF_SUN;
pub const AI = system.AI;
pub const ARCH = system.ARCH;
pub const AT = system.AT;
pub const AT_SUN = system.AT_SUN;
pub const CLOCK = system.CLOCK;
pub const CPU_COUNT = system.CPU_COUNT;
pub const CTL = system.CTL;
pub const DT = system.DT;
pub const E = system.E;
pub const Elf_Symndx = system.Elf_Symndx;
pub const F = system.F;
pub const FD_CLOEXEC = system.FD_CLOEXEC;
pub const Flock = system.Flock;
pub const HOST_NAME_MAX = system.HOST_NAME_MAX;
pub const HW = system.HW;
pub const IFNAMESIZE = system.IFNAMESIZE;
pub const IOV_MAX = system.IOV_MAX;
pub const IP = system.IP;
pub const IPV6 = system.IPV6;
pub const IPPROTO = system.IPPROTO;
pub const IPTOS = system.IPTOS;
pub const KERN = system.KERN;
pub const Kevent = system.Kevent;
pub const MADV = system.MADV;
pub const MAP = system.MAP;
pub const MAX_ADDR_LEN = system.MAX_ADDR_LEN;
pub const MCL = system.MCL;
pub const MFD = system.MFD;
pub const MLOCK = system.MLOCK;
pub const MREMAP = system.MREMAP;
pub const MSF = system.MSF;
pub const MSG = system.MSG;
pub const NAME_MAX = system.NAME_MAX;
pub const NSIG = system.NSIG;
pub const O = system.O;
pub const PATH_MAX = system.PATH_MAX;
pub const POLL = system.POLL;
pub const POSIX_FADV = system.POSIX_FADV;
pub const PR = system.PR;
pub const PROT = system.PROT;
pub const RLIM = system.RLIM;
pub const S = system.S;
pub const SA = system.SA;
pub const SC = system.SC;
pub const SCM = system.SCM;
pub const SEEK = system.SEEK;
pub const SHUT = system.SHUT;
pub const SIG = system.SIG;
pub const SIOCGIFINDEX = system.SIOCGIFINDEX;
pub const SO = system.SO;
pub const SOCK = system.SOCK;
pub const SOL = system.SOL;
pub const IFF = system.IFF;
pub const STDERR_FILENO = system.STDERR_FILENO;
pub const STDIN_FILENO = system.STDIN_FILENO;
pub const STDOUT_FILENO = system.STDOUT_FILENO;
pub const SYS = system.SYS;
pub const Sigaction = system.Sigaction;
/// Windows 没有 `stat` 的概念。
///
/// Linux 上已移除 `stat` 的位定义和包装函数,因为需要维护
/// 各目标和 libc 的不同 stat 结构体,易导致运行时
/// 错误。面向 Linux 的用户应添加编译期检查并使用 statx,
/// 类似于 `Io.File.stat` 的做法。
pub const Stat = switch (native_os) {
.windows => void,
.linux => void,
else => system.Stat,
};
pub const T = system.T;
pub const TCP = system.TCP;
pub const VDSO = system.VDSO;
pub const W = system.W;
pub const _SC = system._SC;
pub const addrinfo = system.addrinfo;
pub const blkcnt_t = system.blkcnt_t;
pub const blksize_t = system.blksize_t;
pub const clock_t = system.clock_t;
pub const clockid_t = system.clockid_t;
pub const cmsghdr = system.cmsghdr;
pub const cmsg_align = system.cmsg_align;
pub const timerfd_clockid_t = system.timerfd_clockid_t;
pub const cpu_set_t = system.cpu_set_t;
pub const dev_t = system.dev_t;
pub const dl_phdr_info = system.dl_phdr_info;
pub const fd_t = system.fd_t;
pub const file_obj = system.file_obj;
pub const gid_t = system.gid_t;
pub const ifreq = system.ifreq;
pub const in_pktinfo = system.in_pktinfo;
pub const in6_pktinfo = system.in6_pktinfo;
pub const ino_t = system.ino_t;
pub const linger = system.linger;
pub const mode_t = system.mode_t;
pub const msghdr = system.msghdr;
pub const msghdr_const = system.msghdr_const;
pub const nfds_t = system.nfds_t;
pub const nlink_t = system.nlink_t;
pub const off_t = system.off_t;
pub const pid_t = system.pid_t;
pub const pollfd = system.pollfd;
pub const port_event = system.port_event;
pub const port_notify = system.port_notify;
pub const port_t = system.port_t;
pub const rlim_t = system.rlim_t;
pub const rlimit = system.rlimit;
pub const rlimit_resource = system.rlimit_resource;
pub const rusage = system.rusage;
pub const sa_family_t = system.sa_family_t;
pub const siginfo_t = system.siginfo_t;
pub const sigset_t = system.sigset_t;
pub const sigrtmin = system.sigrtmin;
pub const sigrtmax = system.sigrtmax;
pub const sockaddr = system.sockaddr;
pub const socklen_t = system.socklen_t;
pub const stack_t = system.stack_t;
pub const time_t = system.time_t;
pub const timespec = system.timespec;
pub const timestamp_t = system.timestamp_t;
pub const timeval = system.timeval;
pub const timezone = system.timezone;
pub const UTIME = system.UTIME;
pub const uid_t = system.uid_t;
pub const user_desc = system.user_desc;
pub const utsname = system.utsname;
pub const termios = system.termios;
pub const CSIZE = system.CSIZE;
pub const NCCS = system.NCCS;
pub const cc_t = system.cc_t;
pub const V = system.V;
pub const speed_t = system.speed_t;
pub const tc_iflag_t = system.tc_iflag_t;
pub const tc_oflag_t = system.tc_oflag_t;
pub const tc_cflag_t = system.tc_cflag_t;
pub const tc_lflag_t = system.tc_lflag_t;
pub const F_OK = system.F_OK;
pub const R_OK = system.R_OK;
pub const W_OK = system.W_OK;
pub const X_OK = system.X_OK;
pub const iovec = extern struct {
base: [*]u8,
len: usize,
};
pub const iovec_const = extern struct {
base: [*]const u8,
len: usize,
};
pub const ACCMODE = switch (native_os) {
// POSIX 对访问模式值有以下说明:
//
// 历史实现中,O_RDONLY 的值为零。因此,
// 无法检测是否同时指定了 O_RDONLY 和另一个
// 选项。后续实现应将 O_RDONLY 和 O_WRONLY 编码为
// 位标志,使 O_RDONLY | O_WRONLY == O_RDWR。
//
// 实际上,Zig 支持的系统中,仅 SerenityOS
// 实现了这一建议。
// https://github.com/SerenityOS/serenity/blob/4adc51fdf6af7d50679c48b39362e062f5a3b2cb/Kernel/API/POSIX/fcntl.h#L28-L30
.serenity => enum(u2) {
NONE = 0,
RDONLY = 1,
WRONLY = 2,
RDWR = 3,
},
else => enum(u2) {
RDONLY = 0,
WRONLY = 1,
RDWR = 2,
},
};
pub const TCSA = enum(c_uint) {
NOW,
DRAIN,
FLUSH,
_,
};
pub const winsize = extern struct {
row: u16,
col: u16,
xpixel: u16,
ypixel: u16,
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const NB = 4;
pub const UN = 8;
};
pub const LOG = struct {
/// 系统不可用
pub const EMERG = 0;
/// 必须立即采取操作
pub const ALERT = 1;
/// 严重情况
pub const CRIT = 2;
/// 错误条件
pub const ERR = 3;
/// 警告条件
pub const WARNING = 4;
/// 正常但值得注意的情况
pub const NOTICE = 5;
/// 信息性
pub const INFO = 6;
/// 调试级别消息
pub const DEBUG = 7;
};
pub const socket_t = fd_t;
/// 从系统函数调用的返回值取得 errno。
///
/// 某些系统上直接从系统调用返回值取得该值;
/// 其他系统上则使用线程局部 errno 变量。因此,
/// 只有紧接在希望观察 errno 的系统函数调用
/// 之后调用,此函数的返回值才是定义明确的。
pub const errno = system.errno;
pub const RebootError = error{
PermissionDenied,
} || UnexpectedError;
pub const RebootCommand = switch (native_os) {
.linux => union(linux.LINUX_REBOOT.CMD) {
RESTART: void,
HALT: void,
CAD_ON: void,
CAD_OFF: void,
POWER_OFF: void,
RESTART2: [*:0]const u8,
SW_SUSPEND: void,
KEXEC: void,
},
else => @compileError("Unsupported OS"),
};
pub fn reboot(cmd: RebootCommand) RebootError!void {
switch (native_os) {
.linux => {
switch (linux.errno(linux.reboot(
.MAGIC1,
.MAGIC2,
cmd,
switch (cmd) {
.RESTART2 => |s| s,
else => null,
},
))) {
.SUCCESS => {},
.PERM => return error.PermissionDenied,
else => |err| return std.posix.unexpectedErrno(err),
}
switch (cmd) {
.CAD_OFF => {},
.CAD_ON => {},
.SW_SUSPEND => {},
.HALT => unreachable,
.KEXEC => unreachable,
.POWER_OFF => unreachable,
.RESTART => unreachable,
.RESTART2 => unreachable,
}
},
else => @compileError("Unsupported OS"),
}
}
pub const RaiseError = UnexpectedError;
pub fn raise(sig: SIG) RaiseError!void {
if (builtin.link_libc) {
switch (errno(system.raise(sig))) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
}
}
if (native_os == .linux) {
// 阻塞所有信号,避免 gettid() 和 kill() 系统调用之间的 `fork`(由信号处理程序发起)
// 触发额外且意外的进程间信号。这种对信号的谨慎处理继承自 Musl。
const filled = linux.sigfillset();
var orig: sigset_t = undefined;
sigprocmask(SIG.BLOCK, &filled, &orig);
const rc = linux.tkill(linux.gettid(), sig);
sigprocmask(SIG.SETMASK, &orig, null);
switch (errno(rc)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
}
}
@compileError("std.posix.raise unimplemented for this target");
}
pub const KillError = error{ ProcessNotFound, PermissionDenied } || UnexpectedError;
pub fn kill(pid: pid_t, sig: SIG) KillError!void {
switch (errno(system.kill(pid, sig))) {
.SUCCESS => return,
.INVAL => unreachable, // 信号无效
.PERM => return error.PermissionDenied,
.SRCH => return error.ProcessNotFound,
else => |err| return unexpectedErrno(err),
}
}
pub const ReadError = std.Io.File.Reader.Error;
/// 返回读取的字节数,可能少于
/// buf.len。读取 0 字节表示文件结束。
/// 如果 `fd` 以非阻塞模式打开,收到 EAGAIN 时
/// 此函数返回 error.WouldBlock。
///
/// Linux 限制单次 `read` 可传输的字节数,在 64 位和 32 位
/// 系统上均为 `0x7ffff000`。这是因为返回值使用有符号 C int,
/// 且最后 `4096` 个值用于存放 errno 错误码。`read` 手册页说明了这一点。
/// Darwin 的上限为 `0x7fffffff`,尝试读取更多字节会返回 EINVAL。
/// 相应的 POSIX 上限是 `maxInt(isize)`。
pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
if (buf.len == 0) return 0;
if (native_os == .windows) @compileError("unsupported OS");
if (native_os == .wasi) @compileError("unsupported OS");
// 防止 EINVAL。
const max_count = switch (native_os) {
.linux => 0x7ffff000,
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => maxInt(i32),
else => maxInt(isize),
};
while (true) {
const rc = system.read(fd, buf.ptr, @min(buf.len, max_count));
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.INTR => continue,
.INVAL => unreachable,
.FAULT => unreachable,
.AGAIN => return error.WouldBlock,
.CANCELED => return error.Canceled,
.BADF => return error.Unexpected, // 释放后使用
.IO => return error.InputOutput,
.ISDIR => return error.IsDir,
.NOBUFS => return error.SystemResources,
.NOMEM => return error.SystemResources,
.NOTCONN => return error.SocketUnconnected,
.CONNRESET => return error.ConnectionResetByPeer,
.TIMEDOUT => return error.Unexpected,
else => |err| return unexpectedErrno(err),
}
}
}
pub const OpenError = std.Io.File.OpenError || error{WouldBlock};
/// 打开文件,必要时创建文件。若被中断则不断重试。
/// `file_path` 相对于已打开的目录句柄 `dir_fd`。
/// Windows 上,`file_path` 应编码为 [WTF-8](https://wtf-8.codeberg.page/)。
/// WASI 上,`file_path` 应编码为有效 UTF-8。
/// 其他平台上,`file_path` 是不规定编码的不透明字节序列。
/// 另请参见 `openatZ`。
pub fn openat(dir_fd: fd_t, file_path: []const u8, flags: O, mode: mode_t) OpenError!fd_t {
if (native_os == .windows) {
@compileError("Windows does not support POSIX; use Windows-specific API or cross-platform std.fs API");
} else if (native_os == .wasi and !builtin.link_libc) {
@compileError("use std.Io instead");
}
const file_path_c = try toPosixPath(file_path);
return openatZ(dir_fd, &file_path_c, flags, mode);
}
/// 打开文件,并可能创建文件。若被中断,则继续重试。
/// `file_path` 相对于已打开的目录句柄 `dir_fd`。
/// Windows 上,`file_path` 应采用 [WTF-8](https://wtf-8.codeberg.page/) 编码。
/// WASI 上,`file_path` 应采用有效 UTF-8 编码。
/// 其他平台上,`file_path` 是不透明的字节序列,没有特定编码。
/// 另见 `openat`。
pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: O, mode: mode_t) OpenError!fd_t {
if (native_os == .windows) {
@compileError("Windows does not support POSIX; use Windows-specific API or cross-platform std.fs API");
} else if (native_os == .wasi and !builtin.link_libc) {
return openat(dir_fd, mem.sliceTo(file_path, 0), flags, mode);
}
const openat_sym = if (lfs64_abi) system.openat64 else system.openat;
while (true) {
const rc = openat_sym(dir_fd, file_path, flags, mode);
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.INTR => continue,
.FAULT => unreachable,
.INVAL => return error.BadPathName,
.BADF => unreachable,
.ACCES => return error.AccessDenied,
.FBIG => return error.FileTooBig,
.OVERFLOW => return error.FileTooBig,
.ISDIR => return error.IsDir,
.LOOP => return error.SymLinkLoop,
.MFILE => return error.ProcessFdQuotaExceeded,
.NAMETOOLONG => return error.NameTooLong,
.NFILE => return error.SystemFdQuotaExceeded,
.NODEV => return error.NoDevice,
.NOENT => return error.FileNotFound,
.SRCH => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.NoSpaceLeft,
.NOTDIR => return error.NotDir,
.PERM => return error.PermissionDenied,
.EXIST => return error.PathAlreadyExists,
.BUSY => return error.DeviceBusy,
.OPNOTSUPP => return error.FileLocksUnsupported,
.AGAIN => return error.WouldBlock,
.TXTBSY => return error.FileBusy,
.NXIO => return error.NoDevice,
.ILSEQ => return error.BadPathName,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn getppid() pid_t {
return system.getppid();
}
pub const GetSockNameError = error{
/// 系统可用资源不足,无法执行操作。
SystemResources,
/// 网络子系统已失败。
NetworkDown,
/// 套接字尚未绑定
SocketNotBound,
FileDescriptorNotASocket,
/// 套接字未连接(仅适用于面向连接的套接字)。
SocketUnconnected,
} || UnexpectedError;
pub fn getpeername(sock: socket_t, addr: *sockaddr, addrlen: *socklen_t) GetSockNameError!void {
if (native_os == .windows) {
@compileError("use std.Io instead");
} else {
const rc = system.getpeername(sock, addr, addrlen);
switch (errno(rc)) {
.SUCCESS => return,
else => |err| return unexpectedErrno(err),
.BADF => unreachable, // 始终存在竞态条件
.FAULT => unreachable,
.INVAL => unreachable, // 无效参数
.NOTSOCK => return error.FileDescriptorNotASocket,
.NOBUFS => return error.SystemResources,
.NOTCONN => return error.SocketUnconnected,
}
}
}
pub const FanotifyInitError = error{
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
SystemResources,
PermissionDenied,
/// 内核无法识别传入的标志,
/// 可能因为内核版本较旧。
UnsupportedFlags,
} || UnexpectedError;
pub fn fanotify_init(flags: std.os.linux.fanotify.InitFlags, event_f_flags: u32) FanotifyInitError!i32 {
const rc = system.fanotify_init(flags, event_f_flags);
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.INVAL => return error.UnsupportedFlags,
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.SystemResources,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub const FanotifyMarkError = error{
MarkAlreadyExists,
IsDir,
NotAssociatedWithFileSystem,
FileNotFound,
SystemResources,
UserMarkQuotaExceeded,
NotDir,
OperationUnsupported,
PermissionDenied,
CrossDevice,
NameTooLong,
} || UnexpectedError;
pub fn fanotify_mark(
fanotify_fd: fd_t,
flags: std.os.linux.fanotify.MarkFlags,
mask: std.os.linux.fanotify.MarkMask,
dirfd: fd_t,
pathname: ?[]const u8,
) FanotifyMarkError!void {
if (pathname) |path| {
const path_c = try toPosixPath(path);
return fanotify_markZ(fanotify_fd, flags, mask, dirfd, &path_c);
} else {
return fanotify_markZ(fanotify_fd, flags, mask, dirfd, null);
}
}
pub fn fanotify_markZ(
fanotify_fd: fd_t,
flags: std.os.linux.fanotify.MarkFlags,
mask: std.os.linux.fanotify.MarkMask,
dirfd: fd_t,
pathname: ?[*:0]const u8,
) FanotifyMarkError!void {
const rc = system.fanotify_mark(fanotify_fd, flags, mask, dirfd, pathname);
switch (errno(rc)) {
.SUCCESS => return,
.BADF => unreachable,
.EXIST => return error.MarkAlreadyExists,
.INVAL => unreachable,
.ISDIR => return error.IsDir,
.NODEV => return error.NotAssociatedWithFileSystem,
.NOENT => return error.FileNotFound,
.NOMEM => return error.SystemResources,
.NOSPC => return error.UserMarkQuotaExceeded,
.NOTDIR => return error.NotDir,
.OPNOTSUPP => return error.OperationUnsupported,
.PERM => return error.PermissionDenied,
.XDEV => return error.CrossDevice,
else => |err| return unexpectedErrno(err),
}
}
pub const MMapError = error{
/// 指定文件的底层文件系统不支持内存映射。
MemoryMappingNotSupported,
/// 文件描述符引用非普通文件;或请求文件映射,
/// 但文件描述符未以读取方式打开;或请求 `MAP.SHARED`
/// 并设置 `PROT_WRITE`,但文件描述符未以 `RDWR` 模式打开;
/// 或设置 `PROT_WRITE`,但文件仅允许追加。
AccessDenied,
/// `prot` 参数请求 `PROT_EXEC`,但映射区域属于
/// 挂载为禁止执行的文件系统中的文件。
PermissionDenied,
LockedMemoryLimitExceeded,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
OutOfMemory,
/// 使用 FIXED_NOREPLACE 标志,但进程已在给定地址映射内存。
MappingAlreadyExists,
} || UnexpectedError;
/// 将文件或设备映射到内存。
/// `length` 无需对齐。
/// 使用映射区域可能产生以下信号:
/// * SIGSEGV:尝试写入只读映射区域。
/// * SIGBUS:尝试访问缓冲区中不对应文件的部分。
pub fn mmap(
ptr: ?[*]align(page_size_min) u8,
length: usize,
prot: PROT,
flags: MAP,
fd: fd_t,
offset: u64,
) MMapError![]align(page_size_min) u8 {
const mmap_sym = if (lfs64_abi) system.mmap64 else system.mmap;
const rc = mmap_sym(ptr, length, prot, @bitCast(flags), fd, @bitCast(offset));
const err: E = if (builtin.link_libc) blk: {
if (rc != std.c.MAP_FAILED) return @as([*]align(page_size_min) u8, @ptrCast(@alignCast(rc)))[0..length];
break :blk @fromBackingInt(@intCast(system._errno().*));
} else blk: {
const err = errno(rc);
if (err == .SUCCESS) return @as([*]align(page_size_min) u8, @ptrFromInt(rc))[0..length];
break :blk err;
};
switch (err) {
.SUCCESS => unreachable,
.TXTBSY => return error.AccessDenied,
.ACCES => return error.AccessDenied,
.PERM => return error.PermissionDenied,
.AGAIN => return error.LockedMemoryLimitExceeded,
.BADF => unreachable, // 始终存在竞态条件。
.OVERFLOW => unreachable, // 长度与偏移之和所需的页数会溢出。
.NODEV => return error.MemoryMappingNotSupported,
.INVAL => unreachable, // mmap() 的参数无效
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.OutOfMemory,
.EXIST => return error.MappingAlreadyExists,
else => return unexpectedErrno(err),
}
}
/// 删除指定地址范围的映射,使之后对
/// 该范围内地址的引用成为无效内存引用。
/// 注意,虽然 POSIX 允许解除已有映射中间一段区域的映射,
/// Zig 的 munmap 函数却不允许,原因有二:
/// * 这违反了 Zig 要求资源释放必须成功的原则。
/// * Windows 的 NtFreeVirtualMemory 函数有此限制。
pub fn munmap(memory: []align(page_size_min) const u8) void {
switch (errno(system.munmap(memory.ptr, memory.len))) {
.SUCCESS => return,
.INVAL => unreachable, // 参数无效。
.NOMEM => unreachable, // 尝试取消映射现有映射中间的某个区域。
else => |e| if (std.options.unexpected_error_tracing) {
std.debug.panic("unexpected errno: {d} ({t})", .{ @backingInt(e), e });
} else unreachable,
}
}
pub const MRemapError = error{
LockedMemoryLimitExceeded,
/// 要么是调用代码存在缺陷,
/// 要么是操作系统滥用了 EINVAL 错误码。
InvalidSyscallParameters,
OutOfMemory,
} || UnexpectedError;
pub fn mremap(
old_address: ?[*]align(page_size_min) u8,
old_len: usize,
new_len: usize,
flags: system.MREMAP,
new_address: ?[*]align(page_size_min) u8,
) MRemapError![]align(page_size_min) u8 {
const rc = system.mremap(old_address, old_len, new_len, flags, new_address);
const err: E = if (builtin.link_libc) blk: {
if (rc != std.c.MAP_FAILED) return @as([*]align(page_size_min) u8, @ptrCast(@alignCast(rc)))[0..new_len];
break :blk @fromBackingInt(@intCast(system._errno().*));
} else blk: {
const err = errno(rc);
if (err == .SUCCESS) return @as([*]align(page_size_min) u8, @ptrFromInt(rc))[0..new_len];
break :blk err;
};
switch (err) {
.SUCCESS => unreachable,
.AGAIN => return error.LockedMemoryLimitExceeded,
.INVAL => return error.InvalidSyscallParameters,
.NOMEM => return error.OutOfMemory,
.FAULT => unreachable,
else => return unexpectedErrno(err),
}
}
pub const MSyncError = error{
UnmappedMemory,
PermissionDenied,
} || UnexpectedError;
pub fn msync(memory: []align(page_size_min) u8, flags: i32) MSyncError!void {
switch (errno(system.msync(memory.ptr, memory.len, flags))) {
.SUCCESS => return,
.PERM => return error.PermissionDenied,
.NOMEM => return error.UnmappedMemory, // 未成功:提供的指针未指向已映射内存
.INVAL => unreachable, // 参数无效。
else => unreachable,
}
}
pub const SysCtlError = error{
PermissionDenied,
SystemResources,
NameTooLong,
UnknownName,
} || UnexpectedError;
pub fn sysctl(
name: []const c_int,
oldp: ?*anyopaque,
oldlenp: ?*usize,
newp: ?*anyopaque,
newlen: usize,
) SysCtlError!void {
if (native_os == .wasi) {
@compileError("sysctl not supported on WASI");
}
if (native_os == .haiku) {
@compileError("sysctl not supported on Haiku");
}
const name_len = cast(c_uint, name.len) orelse return error.NameTooLong;
switch (errno(system.sysctl(name.ptr, name_len, oldp, oldlenp, newp, newlen))) {
.SUCCESS => return,
.FAULT => unreachable,
.PERM => return error.PermissionDenied,
.NOMEM => return error.SystemResources,
.NOENT => return error.UnknownName,
else => |err| return unexpectedErrno(err),
}
}
pub fn getSelfPhdrs() []std.elf.ElfN.Phdr {
const getauxval = if (builtin.link_libc) std.c.getauxval else std.os.linux.getauxval;
assert(getauxval(std.elf.AT.PHENT) == @sizeOf(std.elf.ElfN.Phdr));
const phdrs: [*]std.elf.ElfN.Phdr = @ptrFromInt(getauxval(std.elf.AT.PHDR));
return phdrs[0..getauxval(std.elf.AT.PHNUM)];
}
pub fn dl_iterate_phdr(
context: anytype,
comptime Error: type,
comptime callback: fn (info: *dl_phdr_info, size: usize, context: @TypeOf(context)) Error!void,
) Error!void {
const Context = @TypeOf(context);
const elf = std.elf;
const dl = @import("dynamic_library.zig");
switch (builtin.object_format) {
.elf, .c => {},
else => @compileError("dl_iterate_phdr is not available for this target"),
}
if (builtin.link_libc) {
switch (system.dl_iterate_phdr(struct {
fn callbackC(info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.c) c_int {
const context_ptr: *const Context = @ptrCast(@alignCast(data));
callback(info, size, context_ptr.*) catch |err| return @intFromError(err);
return 0;
}
}.callbackC, @ptrCast(@constCast(&context)))) {
0 => return,
else => |err| return @as(Error, @errorCast(@errorFromInt(@as(@Int(.unsigned, @bitSizeOf(anyerror)), @intCast(err))))),
}
}
var it = dl.linkmap_iterator() catch unreachable;
// 可执行文件没有动态链接段,为整个 ELF 映像创建单个条目。
//
if (it.end()) {
const getauxval = if (builtin.link_libc) std.c.getauxval else std.os.linux.getauxval;
const phdrs = getSelfPhdrs();
var info: dl_phdr_info = .{
.addr = for (phdrs) |phdr| switch (phdr.type) {
.PHDR => break @intFromPtr(phdrs.ptr) - phdr.vaddr,
else => {},
} else unreachable,
.name = switch (getauxval(std.elf.AT.EXECFN)) {
0 => "/proc/self/exe",
else => |name| @ptrFromInt(name),
},
.phdr = phdrs.ptr,
.phnum = @intCast(phdrs.len),
};
return callback(&info, @sizeOf(dl_phdr_info), context);
}
// 回调函数上一次返回的值。
while (it.next()) |entry| {
const phdrs: []elf.ElfN.Phdr = if (entry.addr != 0) phdrs: {
const ehdr: *elf.ElfN.Ehdr = @ptrFromInt(entry.addr);
assert(mem.eql(u8, &ehdr.ident.magic, elf.MAGIC));
const phdrs: [*]elf.ElfN.Phdr = @ptrFromInt(entry.addr + ehdr.phoff);
break :phdrs phdrs[0..ehdr.phnum];
} else getSelfPhdrs();
var info: dl_phdr_info = .{
.addr = entry.addr,
.name = entry.name,
.phdr = phdrs.ptr,
.phnum = @intCast(phdrs.len),
};
try callback(&info, @sizeOf(dl_phdr_info), context);
}
}
pub const SchedGetAffinityError = error{PermissionDenied} || UnexpectedError;
pub fn sched_getaffinity(pid: pid_t) SchedGetAffinityError!cpu_set_t {
var set: cpu_set_t = undefined;
switch (errno(system.sched_getaffinity(pid, @sizeOf(cpu_set_t), &set))) {
.SUCCESS => return set,
.FAULT => unreachable,
.INVAL => unreachable,
.SRCH => unreachable,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub const SigaltstackError = error{
/// 提供的栈大小小于 MINSIGSTKSZ。
SizeTooSmall,
/// 尝试更改正在使用的信号栈。
PermissionDenied,
} || UnexpectedError;
pub fn sigaltstack(ss: ?*const stack_t, old_ss: ?*stack_t) SigaltstackError!void {
switch (errno(system.sigaltstack(ss, old_ss))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => unreachable,
.NOMEM => return error.SizeTooSmall,
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
/// 返回各位均已设置的 sigset_t。
pub fn sigfillset() sigset_t {
if (builtin.link_libc) {
var set: sigset_t = undefined;
switch (errno(system.sigfillset(&set))) {
.SUCCESS => return set,
else => unreachable,
}
}
return system.sigfillset();
}
/// 返回空的 sigset_t。
pub fn sigemptyset() sigset_t {
if (builtin.link_libc) {
var set: sigset_t = undefined;
switch (errno(system.sigemptyset(&set))) {
.SUCCESS => return set,
else => unreachable,
}
}
return system.sigemptyset();
}
pub fn sigaddset(set: *sigset_t, sig: SIG) void {
if (builtin.link_libc) {
switch (errno(system.sigaddset(set, sig))) {
.SUCCESS => return,
else => unreachable,
}
}
system.sigaddset(set, sig);
}
pub fn sigdelset(set: *sigset_t, sig: SIG) void {
if (builtin.link_libc) {
switch (errno(system.sigdelset(set, sig))) {
.SUCCESS => return,
else => unreachable,
}
}
system.sigdelset(set, sig);
}
pub fn sigismember(set: *const sigset_t, sig: SIG) bool {
if (builtin.link_libc) {
const rc = system.sigismember(set, sig);
switch (errno(rc)) {
.SUCCESS => return rc == 1,
else => unreachable,
}
}
return system.sigismember(set, sig);
}
/// 检查并更改信号处理动作。
pub fn sigaction(sig: SIG, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) void {
switch (errno(system.sigaction(sig, act, oact))) {
.SUCCESS => return,
// EINVAL 表示信号无效,或无法更改其动作。对于 POSIX,这表示 SIGKILL/SIGSTOP。对于 illumos 等系统,还包括
// 非标准信号 SIGWAITING、SIGCANCEL 和 SIGLWP。无论是哪种情况,都是程序员错误。
//
.INVAL => unreachable,
else => unreachable,
}
}
/// 设置线程信号掩码。
pub fn sigprocmask(flags: u32, noalias set: ?*const sigset_t, noalias oldset: ?*sigset_t) void {
switch (errno(system.sigprocmask(@bitCast(flags), set, oldset))) {
.SUCCESS => return,
.FAULT => unreachable,
.INVAL => unreachable,
else => unreachable,
}
}
pub const GetHostNameError = error{PermissionDenied} || UnexpectedError;
pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
if (builtin.link_libc) {
switch (errno(system.gethostname(name_buffer, name_buffer.len))) {
.SUCCESS => return mem.sliceTo(name_buffer, 0),
.FAULT => unreachable,
.NAMETOOLONG => unreachable, // HOST_NAME_MAX 可防止这种情况
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
if (native_os == .linux) {
const uts = uname();
const hostname = mem.sliceTo(&uts.nodename, 0);
const result = name_buffer[0..hostname.len];
@memcpy(result, hostname);
return result;
}
@compileError("TODO implement gethostname for this OS");
}
pub fn uname() utsname {
var uts: utsname = undefined;
switch (errno(system.uname(&uts))) {
.SUCCESS => return uts,
.FAULT => unreachable,
else => unreachable,
}
}
pub const PollError = error{
/// 网络子系统已失败。
NetworkDown,
/// 内核没有空间分配文件描述符表。
SystemResources,
} || UnexpectedError;
pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {
if (native_os == .windows) {
@compileError("use std.Io instead");
}
while (true) {
const fds_count = cast(nfds_t, fds.len) orelse return error.SystemResources;
const rc = system.poll(fds.ptr, fds_count, timeout);
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.FAULT => unreachable,
.INTR => continue,
.INVAL => unreachable,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
unreachable;
}
pub const PPollError = error{
/// 操作在完成前被递送的信号中断。
SignalInterrupt,
/// 内核没有空间分配文件描述符表。
SystemResources,
} || UnexpectedError;
pub fn ppoll(fds: []pollfd, timeout: ?*const timespec, mask: ?*const sigset_t) PPollError!usize {
var ts: timespec = undefined;
var ts_ptr: ?*timespec = null;
if (timeout) |timeout_ns| {
ts_ptr = &ts;
ts = timeout_ns.*;
}
const fds_count = cast(nfds_t, fds.len) orelse return error.SystemResources;
const rc = system.ppoll(fds.ptr, fds_count, ts_ptr, mask);
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.FAULT => unreachable,
.INTR => return error.SignalInterrupt,
.INVAL => unreachable,
.NOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub const SetSockOptError = error{
/// 套接字已连接,而指定选项无法在套接字连接期间设置。
AlreadyConnected,
/// 协议不支持该选项。
InvalidProtocolOption,
/// 发送和接收超时值过大,无法容纳于套接字结构的超时字段中。
TimeoutTooBig,
/// 系统可用资源不足,无法完成此调用。
SystemResources,
/// 设置该套接字选项需要更高权限。
PermissionDenied,
OperationUnsupported,
NetworkDown,
FileDescriptorNotASocket,
SocketNotBound,
NoDevice,
} || UnexpectedError;
/// 设置套接字选项。
pub fn setsockopt(fd: socket_t, level: i32, optname: u32, opt: []const u8) SetSockOptError!void {
if (native_os == .windows) {
@compileError("use std.Io instead");
} else {
switch (errno(system.setsockopt(fd, level, optname, opt.ptr, @intCast(opt.len)))) {
.SUCCESS => {},
.BADF => unreachable, // 始终存在竞态条件
.NOTSOCK => unreachable, // 始终存在竞态条件
.INVAL => unreachable,
.FAULT => unreachable,
.DOM => return error.TimeoutTooBig,
.ISCONN => return error.AlreadyConnected,
.NOPROTOOPT => return error.InvalidProtocolOption,
.NOMEM => return error.SystemResources,
.NOBUFS => return error.SystemResources,
.PERM => return error.PermissionDenied,
.NODEV => return error.NoDevice,
.OPNOTSUPP => return error.OperationUnsupported,
else => |err| return unexpectedErrno(err),
}
}
}
pub const MemFdCreateError = error{
SystemFdQuotaExceeded,
ProcessFdQuotaExceeded,
OutOfMemory,
/// 提供的名称超过 `NAME_MAX`,或传入了无效标志。
NameTooLong,
SystemOutdated,
} || UnexpectedError;
pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t {
switch (native_os) {
.linux => {
// memfd_create 仅在 glibc 2.27 及以上版本和 bionic 30 及以上版本中可用。
const use_c = std.c.versionCheck(if (builtin.abi.isAndroid()) .{ .major = 30, .minor = 0, .patch = 0 } else .{ .major = 2, .minor = 27, .patch = 0 });
const sys = if (use_c) std.c else linux;
const rc = sys.memfd_create(name, flags);
switch (sys.errno(rc)) {
.SUCCESS => return @intCast(rc),
.FAULT => unreachable, // name 包含无效内存
.INVAL => return error.NameTooLong, // 或者程序存在缺陷,标志错误
.NFILE => return error.SystemFdQuotaExceeded,
.MFILE => return error.ProcessFdQuotaExceeded,
.NOMEM => return error.OutOfMemory,
else => |err| return unexpectedErrno(err),
}
},
.freebsd => {
if (comptime builtin.os.version_range.semver.max.order(.{ .major = 13, .minor = 0, .patch = 0 }) == .lt)
@compileError("memfd_create is unavailable on FreeBSD < 13.0");
const rc = system.memfd_create(name, flags);
switch (errno(rc)) {
.SUCCESS => return rc,
.BADF => unreachable, // name 参数为 NULL
.INVAL => unreachable, // 名称过长,或标志无效/不受支持。
.MFILE => return error.ProcessFdQuotaExceeded,
.NFILE => return error.SystemFdQuotaExceeded,
.NOSYS => return error.SystemOutdated,
else => |err| return unexpectedErrno(err),
}
},
else => @compileError("target OS does not support memfd_create()"),
}
}
pub fn memfd_create(name: []const u8, flags: u32) MemFdCreateError!fd_t {
var buffer: [NAME_MAX - "memfd:".len - 1:0]u8 = undefined;
if (name.len > buffer.len) return error.NameTooLong;
@memcpy(buffer[0..name.len], name);
buffer[name.len] = 0;
return memfd_createZ(&buffer, flags);
}
pub fn getrusage(who: i32) rusage {
var result: rusage = undefined;
const rc = system.getrusage(who, &result);
switch (errno(rc)) {
.SUCCESS => return result,
.INVAL => unreachable,
.FAULT => unreachable,
else => unreachable,
}
}
pub const TIOCError = error{NotATerminal};
pub const TermiosGetError = TIOCError || UnexpectedError;
pub fn tcgetattr(handle: fd_t) TermiosGetError!termios {
while (true) {
var term: termios = undefined;
switch (errno(system.tcgetattr(handle, &term))) {
.SUCCESS => return term,
.INTR => continue,
.BADF => unreachable,
.NOTTY => return error.NotATerminal,
else => |err| return unexpectedErrno(err),
}
}
}
pub const TermiosSetError = TermiosGetError || error{ProcessOrphaned};
pub fn tcsetattr(handle: fd_t, optional_action: TCSA, termios_p: termios) TermiosSetError!void {
while (true) {
switch (errno(system.tcsetattr(handle, optional_action, &termios_p))) {
.SUCCESS => return,
.BADF => unreachable,
.INTR => continue,
.INVAL => unreachable,
.NOTTY => return error.NotATerminal,
.IO => return error.ProcessOrphaned,
else => |err| return unexpectedErrno(err),
}
}
}
pub const TermioGetPgrpError = TIOCError || UnexpectedError;
/// 返回与给定句柄关联的 TTY 的进程组 ID。
pub fn tcgetpgrp(handle: fd_t) TermioGetPgrpError!pid_t {
while (true) {
var pgrp: pid_t = undefined;
switch (errno(system.tcgetpgrp(handle, &pgrp))) {
.SUCCESS => return pgrp,
.BADF => unreachable,
.INVAL => unreachable,
.INTR => continue,
.NOTTY => return error.NotATerminal,
else => |err| return unexpectedErrno(err),
}
}
}
pub const TermioSetPgrpError = TermioGetPgrpError || error{NotAPgrpMember};
/// 设置给定 TTY 的控制进程组 ID。
/// handle 必须是与调用进程关联的 TTY 的有效 fd_t。
/// pgrp 必须为有效进程组,且调用进程必须是该组成员。
///
pub fn tcsetpgrp(handle: fd_t, pgrp: pid_t) TermioSetPgrpError!void {
while (true) {
switch (errno(system.tcsetpgrp(handle, &pgrp))) {
.SUCCESS => return,
.BADF => unreachable,
.INVAL => unreachable,
.INTR => continue,
.NOTTY => return error.NotATerminal,
.PERM => return TermioSetPgrpError.NotAPgrpMember,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn signalfd(fd: fd_t, mask: *const sigset_t, flags: u32) !fd_t {
const rc = system.signalfd(fd, mask, flags);
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.BADF, .INVAL => unreachable,
.NFILE => return error.SystemFdQuotaExceeded,
.NOMEM => return error.SystemResources,
.MFILE => return error.ProcessResources,
.NODEV => return error.InodeMountFail,
else => |err| return unexpectedErrno(err),
}
}
pub const SyncError = std.Io.File.SyncError;
/// 将所有待写入的文件内容及元数据修改写入全部文件系统。
pub fn sync() void {
system.sync();
}
/// 将全部待写文件内容和元数据修改写入指定文件所在的文件系统。
pub fn syncfs(fd: fd_t) SyncError!void {
const rc = system.syncfs(fd);
switch (errno(rc)) {
.SUCCESS => return,
.BADF, .INVAL, .ROFS => unreachable,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.DQUOT => return error.DiskQuota,
else => |err| return unexpectedErrno(err),
}
}
/// 将指定文件描述符的全部待写文件内容写入底层文件系统,但不一定写入元数据。
pub fn fdatasync(fd: fd_t) SyncError!void {
const rc = system.fdatasync(fd);
switch (errno(rc)) {
.SUCCESS => return,
.BADF, .INVAL, .ROFS => unreachable,
.IO => return error.InputOutput,
.NOSPC => return error.NoSpaceLeft,
.DQUOT => return error.DiskQuota,
else => |err| return unexpectedErrno(err),
}
}
pub const PrctlError = error{
/// 仅可能发生于 PR_SET_SECCOMP/SECCOMP_MODE_FILTER 或
/// PR_SET_MM/PR_SET_MM_EXE_FILE
AccessDenied,
/// 仅可与 PR_SET_MM/PR_SET_MM_EXE_FILE 一起出现
InvalidFileDescriptor,
InvalidAddress,
/// 仅可能发生于 PR_SET_SPECULATION_CTRL、PR_MPX_ENABLE_MANAGEMENT
/// 或 PR_MPX_DISABLE_MANAGEMENT
UnsupportedFeature,
/// 仅可能随 PR_SET_FP_MODE 出现
OperationUnsupported,
PermissionDenied,
} || UnexpectedError;
pub fn prctl(option: PR, args: anytype) PrctlError!u31 {
if (@typeInfo(@TypeOf(args)) != .@"struct")
@compileError("Expected tuple or struct argument, found " ++ @typeName(@TypeOf(args)));
if (args.len > 4)
@compileError("prctl takes a maximum of 4 optional arguments");
var buf: [4]usize = undefined;
{
comptime var i = 0;
inline while (i < args.len) : (i += 1) buf[i] = args[i];
}
const rc = system.prctl(@backingInt(option), buf[0], buf[1], buf[2], buf[3]);
switch (errno(rc)) {
.SUCCESS => return @intCast(rc),
.ACCES => return error.AccessDenied,
.BADF => return error.InvalidFileDescriptor,
.FAULT => return error.InvalidAddress,
.INVAL => unreachable,
.NODEV, .NXIO => return error.UnsupportedFeature,
.OPNOTSUPP => return error.OperationUnsupported,
.PERM, .BUSY => return error.PermissionDenied,
.RANGE => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub const GetrlimitError = UnexpectedError;
pub fn getrlimit(resource: rlimit_resource) GetrlimitError!rlimit {
const getrlimit_sym = if (lfs64_abi) system.getrlimit64 else system.getrlimit;
var limits: rlimit = undefined;
switch (errno(getrlimit_sym(resource, &limits))) {
.SUCCESS => return limits,
.FAULT => unreachable, // 无效指针
.INVAL => unreachable,
else => |err| return unexpectedErrno(err),
}
}
pub const SetrlimitError = error{ PermissionDenied, LimitTooBig } || UnexpectedError;
pub fn setrlimit(resource: rlimit_resource, limits: rlimit) SetrlimitError!void {
const setrlimit_sym = if (lfs64_abi) system.setrlimit64 else system.setrlimit;
switch (errno(setrlimit_sym(resource, &limits))) {
.SUCCESS => return,
.FAULT => unreachable, // 无效指针
.INVAL => return error.LimitTooBig, // 这也可能表示“资源无效”,但该情况应不可达
.PERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub const MincoreError = error{
/// 某内核资源暂时不可用。
SystemResources,
/// vec 指向无效地址。
InvalidAddress,
/// addr 未按页对齐。
InvalidSyscall,
/// 以下任一情况:
/// * length 大于用户空间 TASK_SIZE - addr
/// * addr + length 包含未映射内存
OutOfMemory,
/// 此类 UNIX 内核的当前版本及配置
/// 不提供 mincore 系统调用。
MincoreUnavailable,
} || UnexpectedError;
/// 确定页面是否驻留在内存中。
pub fn mincore(ptr: [*]align(page_size_min) u8, length: usize, vec: [*]u8) MincoreError!void {
return switch (errno(system.mincore(ptr, length, vec))) {
.SUCCESS => {},
.AGAIN => error.SystemResources,
.FAULT => error.InvalidAddress,
.INVAL => error.InvalidSyscall,
.NOMEM => error.OutOfMemory,
.NOSYS => error.MincoreUnavailable,
else => |err| unexpectedErrno(err),
};
}
pub const MadviseError = error{
/// advice 为 MADV.REMOVE,但指定地址范围不是共享可写映射。
AccessDenied,
/// advice 为 MADV.HWPOISON,但调用方没有 CAP_SYS_ADMIN 能力。
PermissionDenied,
/// 某内核资源暂时不可用。
SystemResources,
/// 以下情况之一:
/// * addr 未按页对齐,或 length 为负数
/// * advice 无效
/// * advice 为 MADV.DONTNEED 或 MADV.REMOVE,且指定地址范围
/// 包含锁定页、Huge TLB 页或 VM_PFNMAP 页
/// * advice 为 MADV.MERGEABLE 或 MADV.UNMERGEABLE,但内核未
/// 配置 CONFIG_KSM
/// * advice 为 MADV.FREE 或 MADV.WIPEONFORK,但指定地址范围
/// 包含文件、Huge TLB、MAP.SHARED 或 VM_PFNMAP 范围
InvalidSyscall,
/// (用于 MADV.WILLNEED)将此区域调入内存会超过进程的
/// 最大驻留集大小。
WouldExceedMaximumResidentSetSize,
/// 以下情况之一:
/// * (对于 MADV.WILLNEED)内存不足:换入失败。
/// * 指定范围内的地址当前未映射,或
/// 位于进程地址空间之外。
OutOfMemory,
/// 此 Linux 内核版本及配置不支持
/// madvise 系统调用。
MadviseUnavailable,
/// 操作系统返回了未记录的错误码。
Unexpected,
};
/// 提供内存使用建议。
/// 此系统调用可选,有时配置为禁用。
pub fn madvise(ptr: [*]align(page_size_min) u8, length: usize, advice: u32) MadviseError!void {
switch (errno(system.madvise(ptr, length, advice))) {
.SUCCESS => return,
.PERM => return error.PermissionDenied,
.ACCES => return error.AccessDenied,
.AGAIN => return error.SystemResources,
.BADF => unreachable, // 映射存在,但该区域映射的对象不是文件。
.INVAL => return error.InvalidSyscall,
.IO => return error.WouldExceedMaximumResidentSetSize,
.NOMEM => return error.OutOfMemory,
.NOSYS => return error.MadviseUnavailable,
else => |err| return unexpectedErrno(err),
}
}
pub const PerfEventOpenError = error{
/// perf_event_attr 的 size 值过小,小于 PERF_ATTR_SIZE_VER0;过大,大于页大小;或超过内核支持的大小且额外字节不为零时,返回此错误。
/// 返回 E2BIG 时,内核会将 perf_event_attr 的 size 字段覆盖为其期望的结构体大小。
///
///
///
///
TooBig,
/// 请求的事件需要 CAP_SYS_ADMIN 权限
/// 或更宽松的 perf_event paranoid 设置时返回。无特权
/// 进程可能遇到此错误的常见情况
/// 包括:附加到其他用户拥有的进程;
/// 监控给定 CPU 上的所有进程,即将 pid
/// 参数设为 -1;以及在 paranoid 设置
/// 要求时未设置 exclude_kernel。
/// 此外:
/// 在许多架构(并非全部)上,指定不受支持的
/// exclude_hv、exclude_idle、exclude_user 或 exclude_kernel
/// 设置时也会返回。
/// 与 EACCES 类似,请求事件需要
/// CAP_SYS_ADMIN 权限或更宽松的
/// perf_event paranoid 设置时也可能发生。包括
/// 在内核地址上设置断点,以及从 Linux 3.13 开始
/// 设置内核函数跟踪的跟踪点。
PermissionDenied,
/// 如果其他事件已独占访问 PMU,
/// 则返回此错误。
DeviceBusy,
/// 每个已打开事件使用一个文件描述符。若打开
/// 大量事件,便会达到每进程打开文件描述符
/// 数量的限制,此后将无法再创建
/// 更多事件。
ProcessResources,
EventRequiresUnsupportedCpuFeature,
/// 尝试添加的断点事件数
/// 超过硬件支持数量时返回。
TooManyBreakpoints,
/// 当 sample_type 中设置了 PERF_SAMPLE_STACK_USER,
/// 但硬件不支持时返回。
SampleStackNotSupported,
/// 请求需要特定硬件特性的事件,
/// 但硬件不支持时返回。包括
/// 请求不受支持的低偏移事件、不可用的分支跟踪、
/// 在没有 PMU 中断时请求采样,
/// 以及为软件事件请求分支栈。
EventNotSupported,
/// 请求 PERF_SAMPLE_CALLCHAIN 且 sample_max_stack
/// 大于 /proc/sys/kernel/perf_event_max_stack 中指定的
/// 最大值时返回。
SampleMaxStackOverflow,
/// 尝试附加到不存在的进程时返回。
ProcessNotFound,
} || UnexpectedError;
pub fn perf_event_open(
attr: *system.perf_event_attr,
pid: pid_t,
cpu: i32,
group_fd: fd_t,
flags: usize,
) PerfEventOpenError!fd_t {
if (native_os == .linux) {
// 各 libc 均未公开此函数的系统调用封装
const rc = linux.perf_event_open(attr, pid, cpu, group_fd, flags);
switch (linux.errno(rc)) {
.SUCCESS => return @intCast(rc),
.@"2BIG" => return error.TooBig,
.ACCES => return error.PermissionDenied,
.BADF => unreachable, // group_fd 文件描述符无效。
.BUSY => return error.DeviceBusy,
.FAULT => unreachable, // 段错误。
.INVAL => unreachable, // 错误的属性设置。
.INTR => unreachable, // 对 uprobe 混合使用 perf 与 ftrace 处理
.MFILE => return error.ProcessResources,
.NODEV => return error.EventRequiresUnsupportedCpuFeature,
.NOENT => unreachable, // 类型设置无效。
.NOSPC => return error.TooManyBreakpoints,
.NOSYS => return error.SampleStackNotSupported,
.OPNOTSUPP => return error.EventNotSupported,
.OVERFLOW => return error.SampleMaxStackOverflow,
.PERM => return error.PermissionDenied,
.SRCH => return error.ProcessNotFound,
else => |err| return unexpectedErrno(err),
}
}
}
pub const PtraceError = error{
DeadLock,
DeviceBusy,
InputOutput,
NameTooLong,
OperationUnsupported,
OutOfMemory,
ProcessNotFound,
PermissionDenied,
} || UnexpectedError;
pub fn ptrace(request: u32, pid: pid_t, addr: usize, data: usize) PtraceError!void {
return switch (native_os) {
.windows,
.wasi,
.emscripten,
.haiku,
.illumos,
.plan9,
=> @compileError("ptrace unsupported by target OS"),
.linux => switch (errno(if (builtin.link_libc) std.c.ptrace(
@intCast(request),
pid,
@ptrFromInt(addr),
@ptrFromInt(data),
) else linux.ptrace(request, pid, addr, data, 0))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.FAULT => unreachable,
.INVAL => unreachable,
.IO => return error.InputOutput,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
else => |err| return unexpectedErrno(err),
},
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => switch (errno(std.c.ptrace(
@fromBackingInt(@intCast(request)),
pid,
@ptrFromInt(addr),
@intCast(data),
))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.INVAL => unreachable,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
else => |err| return unexpectedErrno(err),
},
.dragonfly => switch (errno(std.c.ptrace(
@intCast(request),
pid,
@ptrFromInt(addr),
@intCast(data),
))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.INVAL => unreachable,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
else => |err| return unexpectedErrno(err),
},
.freebsd => switch (errno(std.c.ptrace(
@intCast(request),
pid,
@ptrFromInt(addr),
@intCast(data),
))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.INVAL => unreachable,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
.NOENT, .NOMEM => error.OutOfMemory,
.NAMETOOLONG => error.NameTooLong,
else => |err| return unexpectedErrno(err),
},
.netbsd => switch (errno(std.c.ptrace(
@intCast(request),
pid,
@ptrFromInt(addr),
@intCast(data),
))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.INVAL => unreachable,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
.DEADLK => error.DeadLock,
else => |err| return unexpectedErrno(err),
},
.openbsd => switch (errno(std.c.ptrace(
@intCast(request),
pid,
@ptrFromInt(addr),
@intCast(data),
))) {
.SUCCESS => {},
.SRCH => error.ProcessNotFound,
.INVAL => unreachable,
.PERM => error.PermissionDenied,
.BUSY => error.DeviceBusy,
.NOTSUP => error.OperationUnsupported,
else => |err| return unexpectedErrno(err),
},
else => @compileError("std.posix.ptrace unimplemented for target OS"),
};
}
pub const NameToFileHandleAtError = error{
FileNotFound,
NotDir,
OperationUnsupported,
NameTooLong,
Unexpected,
};
pub fn name_to_handle_at(
dirfd: fd_t,
pathname: []const u8,
handle: *std.os.linux.file_handle,
mount_id: *i32,
flags: u32,
) NameToFileHandleAtError!void {
const pathname_c = try toPosixPath(pathname);
return name_to_handle_atZ(dirfd, &pathname_c, handle, mount_id, flags);
}
pub fn name_to_handle_atZ(
dirfd: fd_t,
pathname_z: [*:0]const u8,
handle: *std.os.linux.file_handle,
mount_id: *i32,
flags: u32,
) NameToFileHandleAtError!void {
switch (errno(system.name_to_handle_at(dirfd, pathname_z, handle, mount_id, flags))) {
.SUCCESS => {},
.FAULT => unreachable, // pathname、mount_id 或 handle 位于可访问地址空间之外。
.INVAL => unreachable, // 标志错误,或 handle_bytes 过大
.NOENT => return error.FileNotFound,
.NOTDIR => return error.NotDir,
.OPNOTSUPP => return error.OperationUnsupported,
.OVERFLOW => return error.NameTooLong,
else => |err| return unexpectedErrno(err),
}
}
pub const lfs64_abi = native_os == .linux and builtin.link_libc and (builtin.abi.isGnu() or builtin.abi.isAndroid());
pub const UnexpectedError = std.Io.UnexpectedError;
/// 执行系统调用或其他会设置 errno 的操作后,
/// 遇到意外错误时调用此函数。
pub fn unexpectedErrno(err: E) UnexpectedError {
if (std.options.unexpected_error_tracing) {
std.debug.print("unexpected errno: {d}\n", .{@backingInt(err)});
std.debug.dumpCurrentStackTrace(.{});
}
return error.Unexpected;
}
/// 用于在栈上将切片转换为以空字符结尾的切片。
pub fn toPosixPath(file_path: []const u8) error{NameTooLong}![PATH_MAX - 1:0]u8 {
if (std.debug.runtime_safety) assert(mem.findScalar(u8, file_path, 0) == null);
var path_with_null: [PATH_MAX - 1:0]u8 = undefined;
// 使用 >= 而非 >,为空字节留出空间
if (file_path.len >= PATH_MAX) return error.NameTooLong;
@memcpy(path_with_null[0..file_path.len], file_path);
path_with_null[file_path.len] = 0;
return path_with_null;
}