command.rs
This file
Path
src/exec/command.rs
49 lines · 1.5 KiB · Rust
Last changed by
No buffering cmd output when running on 1 threadMax Trianobefore adoption394e967
History of this fileTake 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<()>, is_multithread: bool) -> ExitCode {11 let output;12 // Spawn the supplied command.13 if is_multithread {14 output = cmd.output();15 } else {16 // This sort of works:17 let child = cmd.spawn().expect("Failed to execute command");18 output = child.wait_with_output();19 }20 21 // Then wait for the command to exit, if it was spawned.22 match output {23 Ok(output) => {24 // While this lock is active, this thread will be the only thread allowed25 // to write its outputs.26 let _lock = out_perm.lock().unwrap();2728 let stdout = io::stdout();29 let stderr = io::stderr();3031 let _ = stdout.lock().write_all(&output.stdout);32 let _ = stderr.lock().write_all(&output.stderr);3334 if output.status.code() == Some(0) {35 ExitCode::Success36 } else {37 ExitCode::GeneralError38 }39 }40 Err(ref why) if why.kind() == io::ErrorKind::NotFound => {41 print_error(format!("Command not found: {:?}", cmd));42 ExitCode::GeneralError43 }44 Err(why) => {45 print_error(format!("Problem while executing command: {}", why));46 ExitCode::GeneralError47 }48 }49}