#3.10. os:::只有部分作業系統才有的功能
本頁內容
跨平台模組(fs、net、process、io)收錄每個桌面作業系統都能做的事。只有部分作業系統才有的功能放在 std::os 之下,每個作業系統家族一個模組,與 Rust 的劃分方式相同:
| 模組 | 存在於 | 收錄 |
|---|---|---|
os::unix | target_family = "unix"(Linux、macOS、FreeBSD) | fs、io、net、process |
os::linux | target_os = "linux" | net、process |
os::windows | target_os = "windows" | fs、io、process |
os::unix 與 os::windows 的 fs 部分(PermissionsExt、DirExt、OsOpenFlags、OsCreateFlags、CreateFileParams 與旗標常數)與檔案型別一起規定於 3.1.1;以下各節涵蓋其餘部分。
模組只存在於它的目標上:在其他任何目標上,use std::os::unix::.. 無法解析。使用它的程式碼寫在相同的 #[cfg] 之下。
#3.10.1. prelude 中的 Ext trait
只有部分作業系統才有的方法,是跨平台型別上的 trait 方法:PermissionsExt 為 fs::Permissions 加上 mode,CommandExt 為 process::Command 加上 process_group,依此類推。在該 trait 存在的目標上,它位於 prelude 中(0.2),所以其方法不需要 use:
| 目標 | 加入 prelude 的名稱 |
|---|---|
| unix | PermissionsExt(os::unix::fs)、CommandExt、ExitStatusExt(os::unix::process) |
| linux | unix 的那些,再加上 ChildExt(os::linux::process)、TcpStreamExt(os::linux::net) |
在其他目標上,該 trait 及其實作不存在,呼叫會得到找不到的錯誤,錯誤會指出該方法需要的 cfg(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")]`
原始控制代碼的 trait(AsRawFd、AsRawHandle、..)不在 prelude 中:在使用處匯入。
#3.10.2. os::unix::io:檔案描述元
// 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 的有 File、Socket、TcpStream、TcpListener、UdpSocket、Unix 通訊端(3.10.4)、ChildStdin / ChildStdout / ChildStderr,以及 Stdin / Stdout / Stderr(0、1、2)。實作 FromRawFd 的有 File(其錯誤以 fd N 稱呼它)與各通訊端;除標準串流之外,每個 AsRawFd 型別都實作 IntoRawFd。from_raw_fd 是 unsafe:fd 必須是開啟的,且不得有其他東西關閉它,否則會有兩個擁有者關閉同一個描述元(第二次關閉可能碰到之後才開啟的檔案)。
描述元仍由控制代碼擁有:關閉控制代碼就會關閉它,之後 as_raw_fd 回傳 -1。into_raw_fd 則是放棄它:控制代碼被消耗(像 let 那樣被移動),沒有任何東西會關閉該描述元,由呼叫端擁有它,可以關閉它,或以 from_raw_fd 交給新的擁有者。以 from_raw_fd 接收的通訊端照原樣使用;阻塞式描述元會讓阻塞呼叫在作業系統中阻塞,而不是在 poll 中(此時逾時與 set_nonblocking 不適用)。
#3.10.3. os::windows::io:控制代碼與通訊端
// 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 的有 File、子行程管道與標準串流(其 GetStdHandle 值);實作 FromRawHandle 的有 File;實作 IntoRawHandle 的有 File 與子行程管道。AsRawSocket、FromRawSocket 與 IntoRawSocket 由 Socket、TcpStream、TcpListener 與 UdpSocket 實作。into_raw_handle / into_raw_socket 像 into_raw_fd(3.10.2)一樣放棄該值。這些值就是 Win32 給出的 HANDLE 與 SOCKET;執行環境如何保存它們是不可見的。不是核心物件控制代碼的 from_raw_handle 值(例如 GetCurrentProcess() 這類虛擬控制代碼)會得到已關閉的 File。
#3.10.4. os::unix::net:Unix 網域通訊端
Unix 網域通訊端有三種型別:UnixListener、UnixStream 與 UnixDatagram。其形式類似 TCP(3.2),但由於只在同一台主機內通訊,它們以檔案路徑作為識別,並提供對應 socketpair(2) 的 pair()。透過 SCM_RIGHTS 傳遞 fd 只在 Unix 通訊端上有意義,所以另外分成 send_with_fd / recv_with_fd。
// std::os::unix::net
struct UnixListener { /* opaque */ }
struct UnixStream { /* opaque */ }
struct UnixDatagram { /* opaque */ }
impl UnixListener {
fn bind(path: Path) throws (IoError) -> UnixListener; // path must not exist yet; backlog 128
fn accept(self) throws (IoError) -> (UnixStream, Path | none); // peer's bound path, none if unnamed
async fn accept_async(ref self) throws (IoError) -> (UnixStream, Path | none);
fn local_addr(self) throws (IoError) -> Path | none;
fn set_nonblocking(self, nb: bool);
fn try_clone(self) throws (IoError) -> UnixListener;
fn close(self) throws (IoError); // throws what the OS reports
}
impl UnixStream {
fn connect(path: Path) throws (IoError) -> UnixStream;
async fn connect_async(path: Path) throws (IoError) -> UnixStream; // on a blocking thread
fn pair() throws (IoError) -> (UnixStream, UnixStream); // socketpair
fn send_with_fd<B: AsBytes>(self, buf: B, fd: RawFd) throws (IoError) -> usize;
fn recv_with_fd(self, buf: SliceMut<u8>) throws (IoError) -> (usize, RawFd | none);
async fn send_with_fd_async<B: AsBytes>(ref self, buf: B, fd: RawFd) throws (IoError) -> usize;
async fn recv_with_fd_async(ref self, buf: SliceMut<u8>) throws (IoError) -> (usize, RawFd | none);
fn peer_addr(self) throws (IoError) -> Path | none;
fn local_addr(self) throws (IoError) -> Path | none;
fn shutdown(self, how: Shutdown) throws (IoError);
async fn shutdown_async(ref self, how: Shutdown) throws (IoError); // shutdown never waits
fn set_read_timeout(self, dur: Duration | none);
fn set_write_timeout(self, dur: Duration | none);
fn set_nonblocking(self, nb: bool);
fn try_clone(self) throws (IoError) -> UnixStream;
fn split(self) -> (ReadHalf<UnixStream>, WriteHalf<UnixStream>); // as TcpStream::split (3.2.1)
fn close(self) throws (IoError); // throws what the OS reports
}
impl ReadHalf<UnixStream> {
fn unsplit(self, w: WriteHalf<UnixStream>) -> UnixStream;
}
impl UnixDatagram {
fn bind(path: Path) throws (IoError) -> UnixDatagram;
fn connect(path: Path) throws (IoError) -> UnixDatagram; // connected to path, itself unbound
async fn connect_async(path: Path) throws (IoError) -> UnixDatagram; // never waits
fn pair() throws (IoError) -> (UnixDatagram, UnixDatagram); // socketpair
fn send<B: AsBytes>(self, buf: B) throws (IoError) -> usize;
fn recv(self, buf: SliceMut<u8>) throws (IoError) -> usize;
fn send_with_fd<B: AsBytes>(self, buf: B, fd: RawFd) throws (IoError) -> usize;
fn recv_with_fd(self, buf: SliceMut<u8>) throws (IoError) -> (usize, RawFd | none);
// + send_async / recv_async / send_with_fd_async / recv_with_fd_async (ref self)
fn local_addr(self) throws (IoError) -> Path | none;
fn set_read_timeout(self, dur: Duration | none);
fn set_write_timeout(self, dur: Duration | none);
fn set_nonblocking(self, nb: bool);
fn close(self) throws (IoError); // throws what the OS reports
}
impl io::Read for UnixStream { ... }
impl io::Write for UnixStream { ... }
impl io::AsyncRead for UnixStream { ... }
impl io::AsyncWrite for UnixStream { ... }
impl io::Close for UnixListener { ... } // and UnixStream, UnixDatagram
impl io::AsyncClose for UnixListener { ... } // and UnixStream, UnixDatagram
impl Drop for UnixListener { ... } // releases on an error path
impl Drop for UnixStream { ... }
impl Drop for UnixDatagram { ... }
// + AsRawFd, FromRawFd, IntoRawFd for all three
3.2.0 的共通規則適用:底層為非阻塞,set_*_timeout 限制阻塞呼叫的時間,*_async 會暫停任務。串流的 connect 只在監聽端的 backlog 已滿時等待;connect_async 在阻塞執行緒上執行它。以 recv_with_fd 收到的描述元屬於呼叫端(close-on-exec);請以 FromRawFd 把它交給擁有者。
#3.10.5. os::unix::process 與 os::linux::process
// 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 為 none;對 Signal 沒有命名的訊號(即時訊號)也是如此。pidfd 仍屬於子行程:wait / try_wait 會關閉它。
#3.10.6. os::linux::net:核心複製
在吞吐量就是成本的地方,例如代理伺服器或檔案伺服器,Linux 核心的複製路徑在 TcpStream 上公開。大多數使用者不需要它們;io::copy 在可行時已經會使用。
// 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 在核心不再需要 buf 時回傳。核心無法固定記憶體分頁,或沒有 MSG_ZEROCOPY 時,位元組會以一般複製傳送。
#3.10.7. os::windows::process:Ctrl-Break
// std::os::windows::process
fn on_ctrl_break(handler: fn() + Send + Sync) throws (IoError);
process::on_signal 轉送有對應 Signal 的主控台事件(Ctrl-C 為 Interrupt,主控台關閉 / 登出 / 關機為 Hangup,3.6.5)。Ctrl-Break 沒有 Unix 的對應項,所以由這個 Windows 專用函式處理:每當主控台送出 Ctrl-Break,handler 就在 nabi-signal 分派執行緒上執行,之後的呼叫會取代它。沒有處理常式時,Ctrl-Break 會結束行程(主控台的預設行為)。
發現錯誤? 在 GitHub 上編輯此頁 最後更新: