rust - 访问子进程的非标准文件描述符

标签 rust

我有一个子进程,该进程在非标准文件描述符(不在fd0/stdin,fd1/stdout,fd2/stderr上)具有输入/输出(管道)。

如何访问它们?我在文档中看不到任何允许这样做的地方,或者我可能丢失了一些东西:https://doc.rust-lang.org/std/process/struct.Stdio.html

它需要在Windows和Mac上运行。

最佳答案

您可以使用标准库中特定于Unix的API来执行此操作,尤其是使用 FromRawFd 特性:

use std::fs::File;
use std::io::Read;
use std::os::unix::io::{FromRawFd, RawFd};

let fd: RawFd = 3; // example non-standard file descriptor
let mut file = unsafe { File::from_raw_fd(fd) };

// ...

请注意,from_raw_fd表示以下内容:

This function is also unsafe as the primitives currently returned have the contract that they are the sole owner of the file descriptor they are wrapping. Usage of this function could accidentally allow violating this contract which can cause memory unsafety in code that relies on it being true.



因此,您需要确保返回的File具有文件描述符的唯一所有权(这就是将函数标记为不安全的原因)。

关于rust - 访问子进程的非标准文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59640128/

相关文章:

c - 为什么从 C 打印时 CString 指针值会改变?

closures - 如何在 Rust 的结构中存储闭包?

syntax - 如何从 as_slice() 更改为 [] 语法?

rust - 有没有办法在匹配中使用自定义模式,例如正则表达式或函数?

rust - 如何防止 Rust 程序 free()ing 不属于它的 C 字节

dynamic - 为什么在 Rust 中使用动态错误而不是枚举很常见?使用编译时变体不好/不可能吗?

vector - 压缩相同类型的向量会导致 map 闭包中的不同类型

regex - 如何使正则表达式宏工作?

rust - Rust 结构文字中的 ".."语法是什么?

rust - 调用返回字符串文字数组的函数,错误为 "cannot return value referencing local variable"