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

后端 未结 2 1364
不思量自难忘°
不思量自难忘° 2021-01-18 23:21

I need to write to file descriptor 3. I have been searching for it but the documentation is quite poor. The only thing that I have found is the use of libc libr

2条回答
  •  孤城傲影
    2021-01-19 00:19

    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, Write},
        os::unix::io::FromRawFd,
    };
    
    fn main() -> io::Result<()> {
        let mut f = unsafe { File::from_raw_fd(3) };
        write!(&mut f, "Hello, world!")?;
        Ok(())
    }
    
    $ target/debug/example 3> /tmp/output
    $ cat /tmp/output
    Hello, world!
    

    from_raw_fd is unsafe because there's no guarantee that the file descriptor is valid or who is actually responsible for that file descriptor.

    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 can I read from a specific raw file descriptor in Rust?

提交回复
热议问题