DEV Community


Posted on

How to invoke system commands using in Rust

If you want to invoke system commands in your Rust program, you need to make use of the std::process::Command module. In this short post, i'll tell you how to use this module. For more infos on Rust you can visit the well documented Rust book

Getting started

We wanna make sure that we import the std::process::Command module. To do that, go to your file.

use std::process::command;

fn main() {
     println!("Hello World!");
Enter fullscreen mode Exit fullscreen mode

spawn, output and status

Before we start invoking a system command, we must distinguish between three different methods to spawn a child process and run system commands.

spawn -> Executes the commands as a child process and returns a handle to it. For more information on how to interact with stdin/stdout check out this answer on stack overflow.

output -> Runs the command as a child process and waits until the command finishes, then collects the output. If you want to print out the output of a command in real time, please refer to the spawn method.

status -> Runs a command as a child process and waits for it to finish and collect its status.

How to structure a command

We will use the command ls as an example

use std::process:Command;

fn main(){
           .expect("failed to execute command");
Enter fullscreen mode Exit fullscreen mode

For more examples visit the offical docs

I hope I could help you and you like my post.

Top comments (0)