问题
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 useCommand::spawn
. Command::spawn
inherits stdin by default. You'll have to useCommand::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