合并子进程 stdout 和 stderr [英] Merge child process stdout and stderr

查看:73
本文介绍了合并子进程 stdout 和 stderr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何合并子进程 stdout 和 stderr?

How do I merge child process stdout and stderr?

以下不起作用,因为stdoutstderr 之间不能共享所有权:

The following does not work since ownership cannot be shared between stdout and stderr:

let pipe = Stdio::piped();
let prog = Command::new("prog")
                        .stdout(pipe)
                        .stderr(pipe)
                        .spawn()
                        .expect("failed to execute prog");

换句话说,shell 中 2>&1 的 Rust 等价物是什么?

In other words, what is the Rust equivalent of 2>&1 in the shell?

推荐答案

My duct crate 支持这个:

My duct crate supports this:

#[macro_use]
extern crate duct;

fn main() {
    cmd!("echo", "hi").stderr_to_stdout().run();
}

做这样的事情的正确方法",duct 在幕后为你做的,是创建一个双端操作系统管道并将它的写入端传递给两个标准输出和标准错误.标准库的Command 类通常支持这种事情,因为Stdio 实现了FromRawFd,但不幸的是,标准库没有公开创建管道.我编写了另一个名为 os_pipe 的 crate 来在内部执行此操作duct,如果你愿意,你可以直接使用它.

The "right way" to do something like this, which duct is doing for you under the covers, is to create a double-ended OS pipe and pass the write end of it to both stdout and stderr. The standard library's Command class supports this sort of thing in general because Stdio implements FromRawFd, but unfortunately the standard library doesn't expose a way to create pipes. I've written another crate called os_pipe to do this inside of duct, and if you want you can use it directly.

这已经在 Linux、Windows 和 macOS 上进行了测试.

这篇关于合并子进程 stdout 和 stderr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆