Executing Child Processes in Rust

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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 with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/DataStructuresandEnumsGroup(["`Data Structures and Enums`"]) rust(("`Rust`")) -.-> rust/ErrorHandlingandDebuggingGroup(["`Error Handling and Debugging`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") rust/ErrorHandlingandDebuggingGroup -.-> rust/panic_usage("`panic! Usage`") subgraph Lab Skills rust/variable_declarations -.-> lab-99273{{"`Executing Child Processes in Rust`"}} rust/string_type -.-> lab-99273{{"`Executing Child Processes in Rust`"}} rust/function_syntax -.-> lab-99273{{"`Executing Child Processes in Rust`"}} rust/expressions_statements -.-> lab-99273{{"`Executing Child Processes in Rust`"}} rust/method_syntax -.-> lab-99273{{"`Executing Child Processes in Rust`"}} rust/panic_usage -.-> lab-99273{{"`Executing Child Processes in Rust`"}} end

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.

Other Rust Tutorials you may like