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
?
You can create a stdin pipe and write the bytes on it.
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(())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With