Waiting for Child Process Completion

RustRustBeginner
Practice Now

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

Introduction

In this lab, you can learn how to wait for a process::Child to finish by calling Child::wait, which will return a process::ExitStatus.

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/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/mutable_variables("`Mutable Variables`") 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`") subgraph Lab Skills rust/variable_declarations -.-> lab-99276{{"`Waiting for Child Process Completion`"}} rust/mutable_variables -.-> lab-99276{{"`Waiting for Child Process Completion`"}} rust/string_type -.-> lab-99276{{"`Waiting for Child Process Completion`"}} rust/function_syntax -.-> lab-99276{{"`Waiting for Child Process Completion`"}} rust/expressions_statements -.-> lab-99276{{"`Waiting for Child Process Completion`"}} rust/method_syntax -.-> lab-99276{{"`Waiting for Child Process Completion`"}} end

Wait

If you'd like to wait for a process::Child to finish, you must call Child::wait, which will return a process::ExitStatus.

use std::process::Command;

fn main() {
    let mut child = Command::new("sleep").arg("5").spawn().unwrap();
    let _result = child.wait().unwrap();

    println!("reached end of main");
}
$ rustc wait.rs && ./wait
## `wait` keeps running for 5 seconds until the `sleep 5` command finishes
reached end of main

Summary

Congratulations! You have completed the Wait lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like