Search code examples
unixiorustfile-descriptor

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


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 library and the fdopen method, but I haven't found any example about how to use it or write on it.

Can anyone provide me an example of writing to a file descriptor in Rust?


Solution

  • 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: