From this answer, I learned that a file descriptor can be read using 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!
How can I achieve the same result without using unsafe
?
I am currently creating a file descriptor like this (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
I would like to replace the test_fd
with something that could read
or better if it could read & close
the provided file descriptor so that I could end with something like:
function test_fd {
/something/in/rust "$@"
}
exec {FD}< <(/path/to/my/app)
zle -F $FD test_fd