docs

你正在阅读 v0.1.2 的文档。Nabi 0.1.2 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#3.10. os:: - what only some OSes have

本页内容

The cross-platform modules (fs, net, process, io) hold what every desktop OS can do. What only some OSes have lives under std::os, in one module per OS family, as Rust splits it:

ModuleExists onHolds
os::unixtarget_family = "unix" (Linux, macOS, FreeBSD)fs, io, net, process
os::linuxtarget_os = "linux"net, process
os::windowstarget_os = "windows"fs, io, process

The fs parts of os::unix and os::windows (PermissionsExt, DirExt, OsOpenFlags, OsCreateFlags, CreateFileParams and the flag constants) are specified with the file types in 3.1.1; the sections below cover the rest.

A module exists only on its targets: on any other target use std::os::unix::.. does not resolve. Code that uses one is written under the same #[cfg].

#3.10.1. Ext traits in the prelude

Methods that only some OSes have are trait methods on the cross-platform types: PermissionsExt adds mode to fs::Permissions, CommandExt adds process_group to process::Command, and so on. On the targets where the trait exists, it is in the prelude (0.2), so its methods need no use:

TargetsPrelude names added
unixPermissionsExt (os::unix::fs), CommandExt, ExitStatusExt (os::unix::process)
linuxthe unix ones, and ChildExt (os::linux::process), TcpStreamExt (os::linux::net)

On other targets the trait and its impls do not exist, and a call is the not-found error that names the cfg the method needs (refs-lang 6.3):

error[E0046]: no method `process_group` found for type `Command`
   = note: `process_group` is only available on unix (`#[cfg(target_family = "unix")]`)
   = help: put the code that uses it under the same `#[cfg(target_family = "unix")]`

The raw-handle traits (AsRawFd, AsRawHandle, ..) are not in the prelude: they are imported where they are used.

#3.10.2. os::unix::io - file descriptors

nabi
// std::os::unix::io
type RawFd = i32;

trait AsRawFd {
    fn as_raw_fd(self) -> RawFd;             // still owned by self; -1 once self is closed
}

trait FromRawFd {
    unsafe fn from_raw_fd(fd: RawFd) -> Self;    // self owns fd from now on
}

trait IntoRawFd {
    fn into_raw_fd(self) -> RawFd;           // the caller owns fd from now on
}

AsRawFd is implemented by File, Socket, TcpStream, TcpListener, UdpSocket, the Unix sockets (3.10.4), ChildStdin / ChildStdout / ChildStderr and Stdin / Stdout / Stderr (0, 1, 2). FromRawFd is implemented by File (its errors name it fd N) and the sockets; IntoRawFd by every AsRawFd type except the standard streams. from_raw_fd is unsafe: fd must be open, and nothing else may close it, or two owners close one descriptor (and the second close may hit a file opened since).

The descriptor stays owned by the handle: closing the handle closes it, and as_raw_fd returns -1 from then on. into_raw_fd gives it up instead: the handle is consumed (moved, as by let), nothing closes the descriptor, and the caller owns it, to close or to hand to a new owner with from_raw_fd. A socket adopted with from_raw_fd is used as it is; a blocking descriptor makes the blocking calls block in the OS rather than in poll (timeouts and set_nonblocking then do not apply).

#3.10.3. os::windows::io - handles and sockets

nabi
// std::os::windows::io
type RawHandle = isize;                  // a Win32 HANDLE, pointer-sized
type RawSocket = u64;                    // a Winsock SOCKET

trait AsRawHandle { fn as_raw_handle(self) -> RawHandle; }       // INVALID_HANDLE_VALUE (-1) once closed
trait FromRawHandle { unsafe fn from_raw_handle(h: RawHandle) -> Self; }
trait AsRawSocket { fn as_raw_socket(self) -> RawSocket; }       // INVALID_SOCKET once closed
trait FromRawSocket { unsafe fn from_raw_socket(s: RawSocket) -> Self; }
trait IntoRawHandle { fn into_raw_handle(self) -> RawHandle; }  // the caller owns it now
trait IntoRawSocket { fn into_raw_socket(self) -> RawSocket; }  // the caller owns it now

AsRawHandle is implemented by File, the child pipes and the standard streams (their GetStdHandle values); FromRawHandle by File; IntoRawHandle by File and the child pipes. AsRawSocket, FromRawSocket and IntoRawSocket are implemented by Socket, TcpStream, TcpListener and UdpSocket. into_raw_handle / into_raw_socket give the value up as into_raw_fd does (3.10.2). The values are the HANDLE and the SOCKET exactly as Win32 gives them; how the runtime keeps them is not visible. A from_raw_handle value that is not a kernel object handle (a pseudo-handle such as GetCurrentProcess()) gives a closed File.

#3.10.4. os::unix::net - Unix domain sockets

Unix domain sockets come in three types: UnixListener, UnixStream and UnixDatagram. Their shape resembles TCP (3.2), but since they communicate only within the same host they use file paths as identifiers, and they provide pair(), corresponding to socketpair(2). Fd passing through SCM_RIGHTS is meaningful only on Unix sockets, so it is split out into send_with_fd / recv_with_fd.

The common rules of 3.2.0 apply: non-blocking underneath, set_*_timeout bounds the blocking calls, *_async suspend the task. A stream connect waits only while the listener's backlog is full; connect_async runs it on a blocking thread. A descriptor received with recv_with_fd is the caller's (close-on-exec); hand it to an owner with FromRawFd.

#3.10.5. os::unix::process and os::linux::process

nabi
// std::os::unix::process
trait CommandExt {
    fn process_group(self, pgid: i32) -> Self;   // 0: a new group the child leads
}
impl CommandExt for Command { .. }

trait ExitStatusExt {
    fn signal(self) -> Signal | none;            // the signal that ended it
}
impl ExitStatusExt for ExitStatus { .. }

fn parent_id() -> u32;                           // getppid

// std::os::linux::process
trait ChildExt {
    fn pidfd(self) throws (IoError) -> RawFd;    // Linux 5.3+; valid until the child is reaped
}
impl ChildExt for Child { .. }

ExitStatusExt::signal is none when the process exited, and also for a signal Signal does not name (a real-time signal). The pidfd stays the child's: wait / try_wait close it.

#3.10.6. os::linux::net - kernel copies

For places where throughput is the cost, such as proxies or file servers, the Linux kernel copy paths are exposed on TcpStream. Most users do not need them; io::copy already uses them where it can.

nabi
// std::os::linux::net
trait TcpStreamExt {
    fn sendfile(self, ref file: File, offset: u64, count: u64) throws (IoError) -> u64;
                                            // sendfile(2): the bytes sent, fewer if the file ends
    fn splice(self, ref src: File, count: u64) throws (IoError) -> u64;
                                            // splice(2) through a kernel pipe, from src's offset
    fn write_zerocopy(self, buf: List<u8>) throws (IoError) -> usize;
                                            // MSG_ZEROCOPY (Linux 4.14+): some prefix of buf, read in place
}
impl TcpStreamExt for TcpStream { .. }

write_zerocopy returns once the kernel no longer needs buf. When the kernel cannot pin the pages, or has no MSG_ZEROCOPY, the bytes are sent with a plain copy.

#3.10.7. os::windows::process - Ctrl-Break

nabi
// std::os::windows::process
fn on_ctrl_break(handler: fn() + Send + Sync) throws (IoError);

process::on_signal routes the console events that have a Signal (Ctrl-C as Interrupt, console close / logoff / shutdown as Hangup, 3.6.5). Ctrl-Break has no Unix counterpart, so it is this Windows-only function: handler runs on the nabi-signal dispatcher thread each time the console sends Ctrl-Break, and a later call replaces it. Without a handler, Ctrl-Break ends the process (the console's default).

Found a mistake? Edit this page on GitHub. Last updated