从`std :: io :: File :: open`获取文件描述符

时间:2014-07-12 20:32:27

标签: c posix rust

我正在为C库编写绑定,我想调用std::io::File::open,因为它已经有错误处理。然后我打算将fd传递给C函数。

我看过std::io::fs,但fd字段与我想象的完全不同。

经过多次挖掘后,我发现native::io::file::FileDesc确实有fn fd(&self) -> fd_t,但似乎我无法从std::io::File的实例访问此内容。

似乎有fs_from_raw_fd方法,它与我需要的完全相反。

2 个答案:

答案 0 :(得分:2)

当前版本的Rust中最接近的是native::io::file::open

use native::io::file::open;
use std::rt::rtio::{Open, Read};
let file = match open(&path.to_c_str(), Open, Read) {
    Ok(file) => file,
    Err(_) => return,
}
let fd = file.fd();

答案 1 :(得分:1)

use std::os::unix::io::AsRawFd; 

let path = Path::new("my.txt");
let display = path.display();

let mut file = match File::open(&path) {
    // The `description` method of `io::Error` returns a string that
    // describes the error
    Err(why) => panic!("couldn't open {}: {}", display,
                                               why.description()),
    Ok(file) => file,
};
println!("file descriptor: {}",file.as_raw_fd());