Rust has abstracted processes as a class that models a sub-process, which is mentally easier to play with compared to C’s explicit fork() and exec().
In Rust, std::process::Command::new() wraps up fork(), execve(), and returns a class that models this subprocess.
For inter-process communication, Stdio::piped() creates a pipe pipe() and duplicates the pipe with dup2() to redirect the stdin, stdout, stderr to accept inputs, get outputs, etc.
1 | pub fn run_command(program: &str, args: &[&str]) -> String { |
In the above example, we created a subprocess to run program with arguments args through method .args(). We also redirected stdout using .stdout(Stdio::piped()) in order to capture its output with .output().unwrap().stdout
1 | pub fn pipe_through_cat(input: &str) -> String { |
The key points are
stdxxx.take()extract out the inner object, leavingNonein-place- all
stdins andstdouts should be dropped beforeprocess.wait()