Search code examples
ruststdout

What's the correct way to forward stdout of a subprocess to the stdout of the current process in Rust?


I'm having a difficulty figuring out how to forward stdout of a command to the current process's stdout. What I currently have is this, but it slurps in all of the content of stdout, and doesn't account for processes writing to stdout in chunks before the process terminates:

let output = Command::new(cmd)
 .args(args)
 .output()
 .expect("Error reading process stdout");

print!(
  "{}",
  String::from_utf8(output.stdout).expect("Invalid output")
);

Is there a way to read this output incrementally and print chunks as they come?


Solution

  • Just use spawn() instead of output(). It will redirect the standard streams (stdin, stdout and stderr) to the parent process.