Skip to content
Myr

ticket.rs

This file

Path

src/exec/ticket.rs

141 lines · 5.0 KiB · Rust

Last changed by

Updates and preparations for v5.0sharkdpbefore adoptione9cf8af

History of this file

Take it

1// Copyright (c) 2017 fd developers2// Licensed under the Apache License, Version 2.03// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0>4// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,5// at your option. All files in the project carrying such6// notice may not be copied, modified, or distributed except7// according to those terms.89use std::env;10use std::process::Command;11use std::sync::{Arc, Mutex};12use std::io;1314lazy_static! {15    /// On non-Windows systems, the `SHELL` environment variable will be used to determine the16    /// preferred shell of choice for execution. Windows will simply use `cmd`.17    static ref COMMAND: (String, &'static str) = if cfg!(target_os = "windows") {18        ("cmd".into(), "/C")19    } else {20        (env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into()), "-c")21    };22}2324/// A state that offers access to executing a generated command.25///26/// The ticket holds a mutable reference to a string that contains the command to be executed.27/// After execution of the the command via the `then_execute()` method, the string will be28/// cleared so that a new command can be written to the string in the future.29pub struct CommandTicket<'a> {30    command: &'a mut String,31    out_perm: Arc<Mutex<()>>,32}3334impl<'a> CommandTicket<'a> {35    pub fn new(command: &'a mut String, out_perm: Arc<Mutex<()>>) -> CommandTicket<'a> {36        CommandTicket { command, out_perm }37    }3839    /// Executes the command stored within the ticket, and40    /// clearing the command's buffer when finished.'41    #[cfg(not(unix))]42    pub fn then_execute(self) {43        use std::process::Stdio;44        use std::io::Write;4546        // Spawn a shell with the supplied command.47        let cmd = Command::new(COMMAND.0.as_str())48            .arg(COMMAND.1)49            .arg(&self.command)50            .stdout(Stdio::piped())51            .stderr(Stdio::piped())52            .output();5354        // Then wait for the command to exit, if it was spawned.55        match cmd {56            Ok(output) => {57                // While this lock is active, this thread will be the only thread allowed58                // to write it's outputs.59                let _lock = self.out_perm.lock().unwrap();6061                let stdout = io::stdout();62                let stderr = io::stderr();6364                let _ = stdout.lock().write_all(&output.stdout);65                let _ = stderr.lock().write_all(&output.stderr);66            }67            Err(why) => eprintln!("fd: exec error: {}", why),68        }6970        // Clear the buffer for later re-use.71        self.command.clear();72    }7374    #[cfg(all(unix))]75    pub fn then_execute(self) {76        use libc::{close, dup2, pipe, STDERR_FILENO, STDOUT_FILENO};77        use std::fs::File;78        use std::os::unix::process::CommandExt;79        use std::os::unix::io::FromRawFd;8081        // Initial a pair of pipes that will be used to82        // pipe the std{out,err} of the spawned process.83        let mut stdout_fds = [0; 2];84        let mut stderr_fds = [0; 2];8586        unsafe {87            pipe(stdout_fds.as_mut_ptr());88            pipe(stderr_fds.as_mut_ptr());89        }9091        // Spawn a shell with the supplied command.92        let cmd = Command::new(COMMAND.0.as_str())93            .arg(COMMAND.1)94            .arg(&self.command)95            // Configure the pipes accordingly in the child.96            .before_exec(move || unsafe {97                // Redirect the child's std{out,err} to the write ends of our pipe.98                dup2(stdout_fds[1], STDOUT_FILENO);99                dup2(stderr_fds[1], STDERR_FILENO);100101                // Close all the fds we created here, so EOF will be sent when the program exits.102                close(stdout_fds[0]);103                close(stdout_fds[1]);104                close(stderr_fds[0]);105                close(stderr_fds[1]);106                Ok(())107            })108            .spawn();109110        // Open the read end of the pipes as `File`s.111        let (mut pout, mut perr) = unsafe {112            // Close the write ends of the pipes in the parent113            close(stdout_fds[1]);114            close(stderr_fds[1]);115            (116                // But create files from the read ends.117                File::from_raw_fd(stdout_fds[0]),118                File::from_raw_fd(stderr_fds[0]),119            )120        };121122        match cmd {123            Ok(mut child) => {124                let _ = child.wait();125126                // Create a lock to ensure that this thread has exclusive access to writing.127                let _lock = self.out_perm.lock().unwrap();128129                // And then write the outputs of the process until EOF is sent to each file.130                let stdout = io::stdout();131                let stderr = io::stderr();132                let _ = io::copy(&mut pout, &mut stdout.lock());133                let _ = io::copy(&mut perr, &mut stderr.lock());134            }135            Err(why) => eprintln!("fd: exec error: {}", why),136        }137138        // Clear the command string's buffer for later re-use.139        self.command.clear();140    }141}