Write to child process' stdin in Rust?

做~自己de王妃 提交于 2020-12-31 05:54:05

问题


Rust's std::process::Command allows configuring the process' stdin via the stdin method, but it appears that that method only accepts existing files or pipes.

Given a slice of bytes, how would you go about writing it to the stdin of a Command?


回答1:


You can create a stdin pipe and write the bytes on it.

  • As Command::output immediately closes the stdin, you'll have to use Command::spawn.
  • Command::spawn inherits stdin by default. You'll have to use Command::stdin to change the behavior.

Here is the example (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(())
}



回答2:


You need to request the use of a pipe at the time you create the subprocess. Then you can write to the write end of the pipe in order to pass data to the subprocess.

Alternatively, you could write the data to a temporary file and specify a File object. This way, you do not have to take of feeding the data piecewise to the subprocess, which can be a bit tricky if you are also reading from its standard output. (There's a risk of deadlocks.)

If an inherited descriptor is used for standard input, the parent process does not necessarily have the capability to inject the data into that.



来源:https://stackoverflow.com/questions/49218599/write-to-child-process-stdin-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!