rust - 在 Rust 中写入子进程的标准输入?

标签 rust subprocess exec stdin

Rust 的 std::process::Command允许通过 stdin 配置进程的标准输入方法,但该方法似乎只接受现有文件或管道。

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

最佳答案

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

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

这是示例(playground):

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

fn main() -> 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")?;
    // Close stdin to finish and avoid indefinite blocking
    drop(child_stdin);
    
    let output = child.wait_with_output()?;

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

    Ok(())
}

关于rust - 在 Rust 中写入子进程的标准输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49218599/

相关文章:

perl - mod_perl与system()或exec()调用或反引号的奇怪行为

generics - 具有泛型类型结构值的结构

python - Windows 上的 subprocess.call 没有启动第二个文件

objective-c - 重新分配父 PID

python - 使用网络浏览器调用的python脚本运行exe

php - 从 python 调用 php 脚本(子进程)

c - 在 C 中发送 bash connectback 问题

concurrency - 在Rust中编写双重检查锁定的正确方法是什么?

performance - num crate 中的大整数实现是否很慢?

rust - 获取错误 "the trait ` std::ops::FnMut<(char,) >` is not implemented for ` std::string::String`"用于简单类型不匹配