Trait CommandExt

trait CommandExt: Sealed

Windows-specific extensions to the process::Command builder.

This trait is sealed: it cannot be implemented outside the standard library. This is so that future additional methods are not breaking changes.

Required Methods

fn creation_flags(self: &mut Self, flags: u32) -> &mut process::Command

Sets the process creation flags to be passed to CreateProcess.

These will always be ORed with CREATE_UNICODE_ENVIRONMENT.

fn show_window(self: &mut Self, cmd_show: u16) -> &mut process::Command

Sets the field wShowWindow of STARTUPINFO that is passed to CreateProcess. Allowed values are the ones listed in https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow

fn force_quotes(self: &mut Self, enabled: bool) -> &mut process::Command

Forces all arguments to be wrapped in quote (") characters.

This is useful for passing arguments to MSYS2/Cygwin based executables: these programs will expand unquoted arguments containing wildcard characters (? and *) by searching for any file paths matching the wildcard pattern.

Adding quotes has no effect when passing arguments to programs that use msvcrt. This includes programs built with both MinGW and MSVC.

fn raw_arg<S: AsRef<OsStr>>(self: &mut Self, text_to_append_as_is: S) -> &mut process::Command

Append literal text to the command line without any quoting or escaping.

This is useful for passing arguments to applications that don't follow the standard C run-time escaping rules, such as cmd.exe /c.

Batch files

Note the cmd /c command line has slightly different escaping rules than batch files themselves. If possible, it may be better to write complex arguments to a temporary .bat file, with appropriate escaping, and simply run that using:

# use std::process::Command;
# let temp_bat_file = "";
# #[allow(unused)]
let output = Command::new("cmd").args(["/c", &format!("\"{temp_bat_file}\"")]).output();

Example

Run a batch script using both trusted and untrusted arguments.

#[cfg(windows)]
// `my_script_path` is a path to known bat file.
// `user_name` is an untrusted name given by the user.
fn run_script(
    my_script_path: &str,
    user_name: &str,
) -> Result<std::process::Output, std::io::Error> {
    use std::io::{Error, ErrorKind};
    use std::os::windows::process::CommandExt;
    use std::process::Command;

    // Create the command line, making sure to quote the script path.
    // This assumes the fixed arguments have been tested to work with the script we're using.
    let mut cmd_args = format!(r#""{my_script_path}" "--features=[a,b,c]""#);

    // Make sure the user name is safe. In particular we need to be
    // cautious of ascii symbols that cmd may interpret specially.
    // Here we only allow alphanumeric characters.
    if !user_name.chars().all(|c| c.is_alphanumeric()) {
        return Err(Error::new(ErrorKind::InvalidInput, "invalid user name"));
    }

    // now we have validated the user name, let's add that too.
    cmd_args.push_str(" --user ");
    cmd_args.push_str(user_name);

    // call cmd.exe and return the output
    Command::new("cmd.exe")
        .arg("/c")
        // surround the entire command in an extra pair of quotes, as required by cmd.exe.
        .raw_arg(&format!("\"{cmd_args}\""))
        .output()
}
fn async_pipes(self: &mut Self, always_async: bool) -> &mut process::Command

When process::Command creates pipes, request that our side is always async.

By default process::Command may choose to use pipes where both ends are opened for synchronous read or write operations. By using async_pipes(true), this behavior is overridden so that our side is always async.

This is important because if doing async I/O a pipe or a file has to be opened for async access.

The end of the pipe sent to the child process will always be synchronous regardless of this option.

Example

#![feature(windows_process_extensions_async_pipes)]
use std::os::windows::process::CommandExt;
use std::process::{Command, Stdio};

# let program = "";

Command::new(program)
    .async_pipes(true)
    .stdin(Stdio::piped())
    .stdout(Stdio::piped())
    .stderr(Stdio::piped());
fn spawn_with_attributes(self: &mut Self, attribute_list: &ProcThreadAttributeList<'_>) -> io::Result<process::Child>

Executes the command as a child process with the given ProcThreadAttributeList, returning a handle to it.

This method enables the customization of attributes for the spawned child process on Windows systems. Attributes offer extended configurability for process creation, but their usage can be intricate and potentially unsafe.

Note

By default, stdin, stdout, and stderr are inherited from the parent process.

Example

#![feature(windows_process_extensions_raw_attribute)]
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::{CommandExt, ProcThreadAttributeList};
use std::process::Command;

# struct ProcessDropGuard(std::process::Child);
# impl Drop for ProcessDropGuard {
#     fn drop(&mut self) {
#         let _ = self.0.kill();
#     }
# }
#
let parent = Command::new("cmd").spawn()?;
let parent_process_handle = parent.as_raw_handle();
# let parent = ProcessDropGuard(parent);

const PROC_THREAD_ATTRIBUTE_PARENT_PROCESS: usize = 0x00020000;
let mut attribute_list = ProcThreadAttributeList::build()
    .attribute(PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &parent_process_handle)
    .finish()
    .unwrap();

let mut child = Command::new("cmd").spawn_with_attributes(&attribute_list)?;
#
# child.kill()?;
# Ok::<(), std::io::Error>(())
fn startupinfo_fullscreen(self: &mut Self, enabled: bool) -> &mut process::Command

When true, sets the STARTF_RUNFULLSCREEN flag on the STARTUPINFO struct before passing it to CreateProcess.

fn startupinfo_untrusted_source(self: &mut Self, enabled: bool) -> &mut process::Command

When true, sets the STARTF_UNTRUSTEDSOURCE flag on the STARTUPINFO struct before passing it to CreateProcess.

fn startupinfo_force_feedback(self: &mut Self, enabled: Option<bool>) -> &mut process::Command

When specified, sets the following flags on the STARTUPINFO struct before passing it to CreateProcess:

  • If Some(true), sets STARTF_FORCEONFEEDBACK
  • If Some(false), sets STARTF_FORCEOFFFEEDBACK
  • If None, does not set any flags
fn inherit_handles(self: &mut Self, inherit_handles: bool) -> &mut process::Command

If this flag is set to true, each inheritable handle in the calling process is inherited by the new process. If the flag is false, the handles are not inherited.

The default value for this flag is true.

Note that inherited handles have the same value and access rights as the original handles. For additional discussion of inheritable handles, see the Remarks section of the CreateProcessW documentation.

Implementors