Introduction
In this lab, we learn about child processes in Rust using the process::Output struct to represent the output of a finished child process and the process::Command struct to build processes. The example code demonstrates how to execute the rustc --version command and handle the output accordingly by checking if the process succeeded or failed.
Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use
main.rs, compile and run it withrustc main.rs && ./main.
Child processes
The process::Output struct represents the output of a finished child process, and the process::Command struct is a process builder.
use std::process::Command;
fn main() {
let output = Command::new("rustc")
.arg("--version")
.output().unwrap_or_else(|e| {
panic!("failed to execute process: {}", e)
});
if output.status.success() {
let s = String::from_utf8_lossy(&output.stdout);
print!("rustc succeeded and stdout was:\n{}", s);
} else {
let s = String::from_utf8_lossy(&output.stderr);
print!("rustc failed and stderr was:\n{}", s);
}
}
(You are encouraged to try the previous example with an incorrect flag passed to rustc)
Summary
Congratulations! You have completed the Child Processes lab. You can practice more labs in LabEx to improve your skills.