如何在 Rust 中通过管道传输命令?

may*_*o19 6 shell command-line command rust

我正在尝试在 shell 中执行命令并获取字符串形式的返回值。我试图执行的命令是ps axww | grep mongod | grep -v grep.

我在互联网上看到过解决方案,但它们没有解释代码,因此很难根据我的需求对其进行定制。

示例:如何处理生锈的夹层管?&两个子进程之间的管道

有人可以提供一个解决方案,并用外行人的术语逐行解释它是如何工作的吗?

Bla*_*ans 15

您需要的是文档,其中他们通过详尽的示例逐行解释了所有内容。改编自它,这是您的代码

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

fn main() {
    let ps_child = Command::new("ps") // `ps` command...
        .arg("axww")                  // with argument `axww`...
        .stdout(Stdio::piped())       // of which we will pipe the output.
        .spawn()                      // Once configured, we actually spawn the command...
        .unwrap();                    // and assert everything went right.
    let grep_child_one = Command::new("grep")
        .arg("mongod")
        .stdin(Stdio::from(ps_child.stdout.unwrap())) // Pipe through.
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let grep_child_two = Command::new("grep")
        .arg("-v")
        .arg("grep")
        .stdin(Stdio::from(grep_child_one.stdout.unwrap()))
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let output = grep_child_two.wait_with_output().unwrap();
    let result = str::from_utf8(&output.stdout).unwrap();
    println!("{}", result);
}
Run Code Online (Sandbox Code Playgroud)

查看操场(当然不会输出任何内容,因为没有名为mongodrunning... 的进程)。