Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 398
rdiaz82 Avatar asked Feb 25 '19 00:02

rdiaz82


People also ask

How to read and write to a file in rust?

In addition to reading and writing to console, Rust allows reading and writing to files. The File struct represents a file. It allows a program to perform read-write operations on a file. All methods in the File struct return a variant of the io::Result enumeration. The commonly used methods of the File struct are listed in the table below −

What is input and output in rust?

Rust - File Input/ Output. In addition to reading and writing to console, Rust allows reading and writing to files. The File struct represents a file. It allows a program to perform read-write operations on a file. All methods in the File struct return a variant of the io::Result enumeration.

What is read_to_string() in rust?

One-line functions are available for reading and writing files in Rust 1.26 and onwards. The std::fs module includes basic techniques for manipulating the contents of the local file system. The read_to_string () function opens files with fewer imports excluding intermediate variables.

What are one-line functions in rust?

One-line functions are available for reading and writing files in Rust 1.26 and onwards. The std::fs module includes basic techniques for manipulating the contents of the local file system.


1 Answers

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?
like image 138
Shepmaster Avatar answered Oct 03 '22 15:10

Shepmaster