windows - 为什么我不能在 Rust 中将 `Stdio::piped()` 与 windows `cmd.exe` 一起使用?

标签 windows cmd rust process

当我尝试启动时 cmd.exe通过以下代码:

use std::process::{Command, Stdio};
use std::io::{BufRead, Write, BufReader};

fn main() {
    let mut child_cmd = Command::new("cmd.exe")  
        // seems it work well with `/bin/bash` in Linux
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())   // Error emitted here. 
        .spawn()
        .unwrap();   
    // do sth. else
}
我想将输出重定向到管道,但它总是报告 The process tried to write to a nonexistent pipe ;当我删除 .stdout(Stdio::piped()) , 没有错误抛出。为什么会发生这种情况?

最佳答案

EvilTak 的 comment就在现场。当您将 STDOUT 重定向到管道时,您还必须将 STDERR 重定向到管道。以下代码不再出错:

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

fn main() {
    let mut child_cmd = Command::new("cmd.exe")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())  // Required when redirecting stdout
        .spawn()
        .unwrap();
    // do sth. else
}
虽然这解决了眼前的问题,但我不确定是什么导致了它。看着CreateProcessW函数和 STARTUPINFOW它接受的结构,看起来标准 I/O 重定向是一个全有或全无的选项,由 STARTF_USESTDHANDLES 指定。旗帜。
事实Python exhibits the same behavior表明这实际上是 Windows API 或 cmd.exe 实现的一个特性。
无论哪种方式,我都没有进行任何广泛的研究来弄清楚这里到底发生了什么。

关于windows - 为什么我不能在 Rust 中将 `Stdio::piped()` 与 windows `cmd.exe` 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68927669/

相关文章:

generics - 如何对泛型添加约束

c++ - 哪个 gcc 发行版支持 __declspec(dllexport) _cdecl 和 _stdcall

c# - 如何在屏幕中央显示工具提示?

linux - 如何解决这个不明确的重定向错误

android - 通过cmd创建android项目

batch-file - cmd命令以数字顺序转储文件列表

rust - 在 Rust 中为切片分配一个值的惯用方法是什么?

ssl - 为 SNI Rust Web 服务器实现多个 TLS 证书和私钥的正确方法是什么?

c++ - 混合来自不同编译器的 C++ 代码

windows - 在 Weblogic 中使用本地版本的 ANT 和 JUNIT 运行 ant build