expression

Capture a native error immediately

On Linux, a failed libc read reports an error through errno. Capture it immediately after the failing call, before another native call can change it. An empty nonblocking socket with its peer still open reports WouldBlock. Compare the portable Rust error kind rather than a hard-coded errno value. Expected stdout (not executed): would block: true, native code present: true Common mistake: Reading errno after an unrelated call or assuming every io::Error contains an OS code. Run only in the isolated fixture runner, not a public code playground.

Formal Syntax & Structure

rust syntaxrust
io::Error::last_os_error(); error.kind(); error.raw_os_error()

Working Example

Example Snippetrust
use std::{ffi::{c_int,c_void}, io::{self,ErrorKind}, os::{fd::AsRawFd,unix::net::UnixStream}};unsafe extern "C" { fn read(fd: c_int, buf: *mut c_void, count: usize) -> isize; }fn main() -> io::Result<()> {    let (_peer, reader) = UnixStream::pair()?;    reader.set_nonblocking(true)?;    let mut b = [0u8; 1];    // SAFETY: reader is alive and b provides one writable byte.    let n = unsafe { read(reader.as_raw_fd(), b.as_mut_ptr().cast(), b.len()) };    assert!(n < 0);    let err = io::Error::last_os_error();    assert_eq!(err.kind(), ErrorKind::WouldBlock);    println!("would block: {}, native code present: {}", err.kind()==ErrorKind::WouldBlock, err.raw_os_error().is_some());    Ok(())}
Rust Reference