How can I read from a specific raw file descriptor in Rust?

前端 未结 3 1527
小鲜肉
小鲜肉 2020-12-10 15:00

Editor\'s note: This question is for a version of Rust prior to 1.0. Some answers have been updated to cover Rust 1.0 or up, but not all.

<
3条回答
  •  感情败类
    2020-12-10 15:54

    As of Rust 1.1, you can use FromRawFd to create a File from a specific file descriptor, but only on UNIX-like operating systems:

    use std::{
        fs::File,
        io::{self, Read},
        os::unix::io::FromRawFd,
    };
    
    fn main() -> io::Result<()> {
        let mut f = unsafe { File::from_raw_fd(3) };
        let mut input = String::new();
        f.read_to_string(&mut input)?;
    
        println!("I read: {}", input);
    
        Ok(())
    }
    
    $ cat /tmp/output
    Hello, world!
    $ target/debug/example 3< /tmp/output
    I read: Hello, world!
    

    from_raw_fd is unsafe:

    This function is also unsafe as the primitives currently returned have the contract that they are the sole owner of the file descriptor they are wrapping. Usage of this function could accidentally allow violating this contract which can cause memory unsafety in code that relies on it being true.

    The created File will assume ownership of the file descriptor: when the File goes out of scope, the file descriptor will be closed. You can avoid this by using either IntoRawFd or mem::forget.

    See also:

    • How do I write to a specific raw file descriptor from Rust?

提交回复
热议问题