【发布时间】:2019-06-12 18:18:12
【问题描述】:
从this answer了解到,可以使用unsafe读取文件描述符:
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!
如何在不使用unsafe 的情况下获得相同的结果?
我目前正在创建这样的文件描述符(zsh shell):
function test_fd {
if ! read -r line <&$1; then
line="[Read on fd $1 failed]"
fi
echo $line
# Remove the handler and close the fd
zle -F $1
exec {1}<&-
}
exec {FD}< <(/path/to/my/app)
zle -F $FD test_fd
我想将test_fd 替换为可以read 的东西,或者如果它可以read & close 提供的文件描述符则更好,这样我就可以以如下内容结束:
function test_fd {
/something/in/rust "$@"
}
exec {FD}< <(/path/to/my/app)
zle -F $FD test_fd
【问题讨论】:
-
在你的情况下这种不安全的做法看起来很安全
标签: rust file-descriptor