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

Editor's Note: This question applies to Rust versions prior to 1.0. Some answers have been updated to cover Rust 1.0 or higher, but not all.

I am writing a socket activated systemd service in Rust. My process is passed by the open systemd file descriptor.

Are there any Rust IO functions that accept a raw file descriptor?

I use Rust at night until Rust 1.0.

+5
source share
3 answers

, , , libc crate .

FileDesc . . RFC . std::os::unix Fd, , , .

+2

Rust 1.1, FromRawFd File , UNIX- :

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 :

, , , . , , .

File : File , . , IntoRawFd mem::forget.

:

+1

: Rust 1.0 Rust 1.0.

, native : ( "1" - 1 - stdout)

extern crate native;
use native::io::file::FileDesc as FileDesc;

fn main() 
{
  let mut f = FileDesc::new(1, true);
  let buf = "Hello, world!\n".as_bytes();

  f.inner_write(buf);
}

( rustc 0.13.0-nightly. , inner_write , write libstd)

native FileDesc, std::sys::fs::FileDesc ...

0

Source: https://habr.com/ru/post/1569106/


All Articles