Skip to content
Myr

command.rs

This file

Path

src/exec/command.rs

42 lines · 1.3 KiB · Rust

Last changed by

Proper error handling within walk.rssharkdpbefore adoption4590ae8

History of this file

Take it

1use std::io;2use std::io::Write;3use std::process::Command;4use std::sync::Mutex;56use crate::error::print_error;7use crate::exit_codes::ExitCode;89/// Executes a command.10pub fn execute_command(mut cmd: Command, out_perm: &Mutex<()>) -> ExitCode {11    // Spawn the supplied command.12    let output = cmd.output();1314    // Then wait for the command to exit, if it was spawned.15    match output {16        Ok(output) => {17            // While this lock is active, this thread will be the only thread allowed18            // to write its outputs.19            let _lock = out_perm.lock().unwrap();2021            let stdout = io::stdout();22            let stderr = io::stderr();2324            let _ = stdout.lock().write_all(&output.stdout);25            let _ = stderr.lock().write_all(&output.stderr);2627            if output.status.code() == Some(0) {28                ExitCode::Success29            } else {30                ExitCode::GeneralError31            }32        }33        Err(ref why) if why.kind() == io::ErrorKind::NotFound => {34            print_error(format!("Command not found: {:?}", cmd));35            ExitCode::GeneralError36        }37        Err(why) => {38            print_error(format!("Problem while executing command: {}", why));39            ExitCode::GeneralError40        }41    }42}