我有一个子进程,该进程在非标准文件描述符(不在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/