如何从Rust写入特定的原始文件描述符? [英] How do I write to a specific raw file descriptor from Rust?
问题描述
我需要写文件描述符3.我一直在搜索它,但是文档却很差.我发现的唯一一件事就是使用了libc
库和fdopen
方法,但是我还没有找到任何有关如何使用它或在上面写东西的示例.
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.
任何人都可以给我提供一个在Rust中写入文件描述符的示例吗?
Can anyone provide me an example of writing to a file descriptor in Rust?
推荐答案
您可以使用 File
来自特定的文件描述符,但仅在类似UNIX的操作系统上:
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
是不安全的,因为不能保证文件描述符有效或由谁真正负责该文件描述符.
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.
创建的File
将承担文件描述符的所有权:当File
超出范围时,文件描述符将被关闭.您可以通过使用 IntoRawFd
或 mem::forget
.
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
.
另请参阅:
这篇关于如何从Rust写入特定的原始文件描述符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!