Is there any way to `clone` a `std::process::Command`?

Is there any way to clone a std::process::Command? If not, why can't it be implemented as a Clone?
I read the document and found that std::process::Command does not implement Clone, which confuses me.

1 Like

You can clone the exact settings of one Command into another one with this function:

use std::process::Command;

pub fn clone_command(cmd: &Command) -> Command {
    let mut cmd_clone = Command::new(cmd.get_program());
    
    cmd_clone.args(cmd.get_args());
    
    for (k, v) in cmd.get_envs() {
        match v {
            Some(v) => cmd_clone.env(k, v),
            None => cmd_clone.env_remove(k),
        };
    }
    
    if let Some(current_dir) = cmd.get_current_dir() {
        cmd_clone.current_dir(current_dir);
    }
    
    cmd_clone
}

Note that you can spawn multiple child processes from the same Command instance, so you might not even need to clone the Command depending on how you are using it.

8 Likes

Thanks!

1 Like

It's not possible to implement Clone for Command due to std::os::unix::process::CommandExt::pre_exec method.

This method stores closure inside a command instance, and there is no bound for that closure saying it is cloneable.

2 Likes