expression

Read bytes through a native C ABI

Linux exposes read through libc; this is a C library call that normally enters the kernel, not an inline CPU syscall instruction. Borrow a live socket descriptor, provide writable initialized storage and check the signed result before conversion. Prefer safe Rust Read in application code. The writer is a local socket pair, never a production descriptor. Expected stdout (not executed): bytes: 1, value: 88 Common mistake: Casting a negative result to usize before checking it, or closing a borrowed descriptor. Run only in the isolated fixture runner, not a public code playground.

Formal Syntax & Structure

rust syntaxrust
unsafe extern "C" { fn read(fd: c_int, buf: *mut c_void, count: usize) -> isize; }

Working Example

Example Snippetrust
use std::{ffi::{c_int,c_void}, io::{self,Write}, 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 (mut writer, reader) = UnixStream::pair()?;    writer.write_all(b"X")?;    let mut byte = [0u8; 1];    // SAFETY: reader owns a live fd; byte is writable for exactly one byte.    let n = unsafe { read(reader.as_raw_fd(), byte.as_mut_ptr().cast(), byte.len()) };    if n < 0 { return Err(io::Error::last_os_error()); }    println!("bytes: {n}, value: {}", byte[0]);    Ok(())}
Rust Reference