写给孩子的过程'斯坦德在鲁斯特?

时间:2018-03-11 09:37:10

标签: rust subprocess exec stdin

Rust std::process::Command允许配置流程' stdin通过stdin方法,但似乎该方法只接受现有文件或管道。

给定一小部分字节,您如何将其写入Command的标准输入?

2 个答案:

答案 0 :(得分:0)

您需要在创建子流程时请求使用管道。然后,您可以写入管道的写入端,以便将数据传递给子流程。

或者,您可以将数据写入临时文件并指定File对象。这样,您不必将数据分段提供给子进程,如果您还要从其标准输出中读取,这可能有点棘手。 (存在死锁的风险。)

如果继承的描述符用于标准输入,则父进程不一定能够将数据注入其中。

答案 1 :(得分:0)

您可以创建一个stdin管道并在其上写入字节。

  • Command::output立即关闭标准输入时,您必须使用Command::spawn
  • Command::spawn默认继承stdin。您必须使用Command::stdin来更改行为。

以下是示例(playground):

use std::io::{self, Write};
use std::process::{exit, Command, Stdio};

fn main() {
    main2().unwrap_or_else(|e| {
        eprintln!("{}", e);
        exit(1);
    })
}

fn main2() -> io::Result<()> {
    let mut child = Command::new("cat")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()?;

    {
        let child_stdin = child.stdin.as_mut().unwrap();
        child_stdin.write_all(b"Hello, world!\n")?;
    }

    let output = child.wait_with_output()?;

    println!("output = {:?}", output);

    Ok(())
}
相关问题