用安全的Rust将两个进程的标准输入和标准输出对接起来

编程语言 2026-07-11

我想实现类似于 这个答案 的效果——让一个子进程的标准输出连接到另一个子进程的标准输入。

use std::error::Error;
use std::process::{Command, Stdio};

fn main() -> Result<(), Box<dyn Error>> {
    let child1 = Command::new("ls")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();

    let mut child2 = Command::new("wc")
        .stdin(Stdio::from(child1.stdout.unwrap()))
        .spawn()
        .unwrap();

    child1.wait()?;
    child2.wait()?;
    Ok(())
}

然而我也想把 stdoutchild2 连接到 stdinchild1。同一个问题中的另一个回答提供了一个 unsafe 的解决方案。有没有安全的方法来实现?最好不要使用额外的线程。

解决方案

啊,也许像这样。至少能编译通过。我还没有真正测试过它是否能工作!

use std::error::Error;
use std::process::{Command, Stdio};

fn main() -> Result<(), Box<dyn Error>> {
    let mut child1 = Command::new("cmd1")
        .stdout(Stdio::piped())
        .stdin(Stdio::piped())
        .spawn()
        .unwrap();

    let stdout = child1.stdout.take().unwrap();
    let stdin = child1.stdin.take().unwrap();

    let mut child2 = Command::new("cmd2")
        .stdin(Stdio::from(stdout))
        .stdout(Stdio::from(stdin))
        .spawn()
        .unwrap();

    child1.wait()?;
    child2.wait()?;
    Ok(())
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章