home ~ projects ~ socials

Pipe A String To STDIN Of An External Process In Rust

#![allow(unused)]
use std::process::{Command, Stdio};
use std::io::{Error, Write};

fn main() {
  match write_to_stdin() {
    Ok(response) => println!("{}", response),
    Err(e) => println!("{}", e)
  }
}

fn write_to_stdin() -> Result<String, Error> {
  let mut cmd = Command::new("cat")
    .stdin(Stdio::piped())
    .stdout(Stdio::piped())
    .spawn()?;
  let cmd_stdin = cmd.stdin.as_mut().unwrap();
  cmd_stdin.write_all(b"Hello, world!")?;
  let output = cmd.wait_with_output()?;
  Ok(String::from_utf8(output.stdout).unwrap())
}
Output:
Hello, world!
-- end of line --

References