Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write to child process' stdin in Rust?

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?

like image 229
joshlf Avatar asked Mar 11 '18 09:03

joshlf


1 Answers

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(())
}
like image 67
Masaki Hara Avatar answered Oct 20 '22 22:10

Masaki Hara