Skip to main content

Command

Struct Command 

Source
pub struct Command { /* private fields */ }
Expand description

A reusable description of a Windows process launch.

Handles embedded by Self::arg_handle and Self::env_handle are privately duplicated when configured. Each spawn duplicates those handles again into the actual parent process and only then lowers their numeric values to decimal text.

§Examples

Run a command to completion and capture what it wrote, terminating any descendants it leaves behind:

use windows_spawn::{Command, DropPolicy, SpawnOptions};

// `.bat` and `.cmd` are rejected, so a shell boundary is always explicit.
let shell = std::env::var_os("COMSPEC").expect("COMSPEC is set on Windows");
let mut command = Command::new(shell);
command.args(["/D", "/S", "/C"]).raw_arg("echo hello");

let output = command.output_with(SpawnOptions::new().drop_policy(DropPolicy::KillTree))?;

assert!(output.status.success());
assert!(String::from_utf8_lossy(&output.stdout).contains("hello"));

Implementations§

Source§

impl Command

Source

pub fn new<S: AsRef<OsStr>>(program: S) -> Self

Creates a command which will execute program.

Examples found in repository?
examples/managed_output.rs (line 7)
4fn main() -> std::io::Result<()> {
5    use windows_spawn::{Command, DropPolicy, SpawnOptions};
6
7    let mut command = Command::new(r"C:\Windows\System32\cmd.exe");
8    command
9        .args(["/D", "/S", "/C"])
10        .raw_arg("echo managed output");
11    let output = command.output_with(SpawnOptions::new().drop_policy(DropPolicy::KillTree))?;
12
13    assert!(output.status.success());
14    print!("{}", String::from_utf8_lossy(&output.stdout));
15    Ok(())
16}
More examples
Hide additional examples
examples/handle_handoff.rs (line 10)
4fn main() -> std::io::Result<()> {
5    use std::fs::File;
6
7    use windows_spawn::Command;
8
9    let log = File::create("worker.log")?;
10    let mut command = Command::new("worker.exe");
11    command.arg("--log-handle").arg_handle(&log)?;
12
13    // arg_handle stored a private non-inheritable duplicate. The worker
14    // protocol parses the following decimal argument as its borrowed handle.
15    drop(log);
16    let status = command.status()?;
17    assert!(status.success());
18    Ok(())
19}
examples/suspended_inspection.rs (line 9)
4fn main() -> std::io::Result<()> {
5    use std::os::windows::io::AsHandle;
6
7    use windows_spawn::Command;
8
9    let mut command = Command::new(r"C:\Windows\System32\cmd.exe");
10    command.args(["/D", "/C", "exit /b 0"]);
11
12    let suspended = command.spawn_suspended()?;
13    println!("created suspended process {}", suspended.id());
14    let _process = suspended.as_handle();
15    let _primary_thread = suspended.primary_thread_handle();
16
17    let mut child = suspended.resume()?;
18    assert!(child.wait()?.success());
19    Ok(())
20}
Source

pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self

Appends a normally quoted argument.

Examples found in repository?
examples/handle_handoff.rs (line 11)
4fn main() -> std::io::Result<()> {
5    use std::fs::File;
6
7    use windows_spawn::Command;
8
9    let log = File::create("worker.log")?;
10    let mut command = Command::new("worker.exe");
11    command.arg("--log-handle").arg_handle(&log)?;
12
13    // arg_handle stored a private non-inheritable duplicate. The worker
14    // protocol parses the following decimal argument as its borrowed handle.
15    drop(log);
16    let status = command.status()?;
17    assert!(status.success());
18    Ok(())
19}
Source

pub fn args<I, S>(&mut self, args: I) -> &mut Self
where I: IntoIterator<Item = S>, S: AsRef<OsStr>,

Appends multiple normally quoted arguments.

Examples found in repository?
examples/managed_output.rs (line 9)
4fn main() -> std::io::Result<()> {
5    use windows_spawn::{Command, DropPolicy, SpawnOptions};
6
7    let mut command = Command::new(r"C:\Windows\System32\cmd.exe");
8    command
9        .args(["/D", "/S", "/C"])
10        .raw_arg("echo managed output");
11    let output = command.output_with(SpawnOptions::new().drop_policy(DropPolicy::KillTree))?;
12
13    assert!(output.status.success());
14    print!("{}", String::from_utf8_lossy(&output.stdout));
15    Ok(())
16}
More examples
Hide additional examples
examples/suspended_inspection.rs (line 10)
4fn main() -> std::io::Result<()> {
5    use std::os::windows::io::AsHandle;
6
7    use windows_spawn::Command;
8
9    let mut command = Command::new(r"C:\Windows\System32\cmd.exe");
10    command.args(["/D", "/C", "exit /b 0"]);
11
12    let suspended = command.spawn_suspended()?;
13    println!("created suspended process {}", suspended.id());
14    let _process = suspended.as_handle();
15    let _primary_thread = suspended.primary_thread_handle();
16
17    let mut child = suspended.resume()?;
18    assert!(child.wait()?.success());
19    Ok(())
20}
Source

pub fn raw_arg<S: AsRef<OsStr>>(&mut self, text: S) -> &mut Self

Appends text verbatim to the Windows command line.

The text is separated from the preceding element by one space but is otherwise neither quoted nor escaped.

Examples found in repository?
examples/managed_output.rs (line 10)
4fn main() -> std::io::Result<()> {
5    use windows_spawn::{Command, DropPolicy, SpawnOptions};
6
7    let mut command = Command::new(r"C:\Windows\System32\cmd.exe");
8    command
9        .args(["/D", "/S", "/C"])
10        .raw_arg("echo managed output");
11    let output = command.output_with(SpawnOptions::new().drop_policy(DropPolicy::KillTree))?;
12
13    assert!(output.status.success());
14    print!("{}", String::from_utf8_lossy(&output.stdout));
15    Ok(())
16}
Source

pub fn arg_handle<T: AsHandle>(&mut self, handle: &T) -> Result<&mut Self>

Appends a handle argument whose child-table value is lowered at spawn.

§Errors

Returns an error if the source handle cannot be duplicated.

Examples found in repository?
examples/handle_handoff.rs (line 11)
4fn main() -> std::io::Result<()> {
5    use std::fs::File;
6
7    use windows_spawn::Command;
8
9    let log = File::create("worker.log")?;
10    let mut command = Command::new("worker.exe");
11    command.arg("--log-handle").arg_handle(&log)?;
12
13    // arg_handle stored a private non-inheritable duplicate. The worker
14    // protocol parses the following decimal argument as its borrowed handle.
15    drop(log);
16    let status = command.status()?;
17    assert!(status.success());
18    Ok(())
19}
Source

pub fn env<K, V>(&mut self, key: K, value: V) -> &mut Self
where K: AsRef<OsStr>, V: AsRef<OsStr>,

Sets one environment variable.

Source

pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
where I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>,

Sets multiple environment variables.

Source

pub fn env_handle<K: AsRef<OsStr>, T: AsHandle>( &mut self, key: K, handle: &T, ) -> Result<&mut Self>

Sets an environment variable to a handle’s child-table numeric value.

§Errors

Returns an error if the source handle cannot be duplicated.

Source

pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Self

Removes an environment variable case-insensitively.

Source

pub fn env_clear(&mut self) -> &mut Self

Clears the inherited environment and prior recorded modifications.

Source

pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self

Sets the child working directory.

Source

pub fn stdin<T: Into<Stdio>>(&mut self, stdio: T) -> &mut Self

Configures standard input.

Source

pub fn stdout<T: Into<Stdio>>(&mut self, stdio: T) -> &mut Self

Configures standard output.

Source

pub fn stderr<T: Into<Stdio>>(&mut self, stdio: T) -> &mut Self

Configures standard error.

Source

pub fn get_program(&self) -> &OsStr

Returns the originally configured program.

Source

pub fn get_current_dir(&self) -> Option<&Path>

Returns the configured working directory.

Source

pub fn spawn(&mut self) -> Result<Child>

Spawns with default options.

§Errors

Returns validation, resource-acquisition, or process-creation errors.

Source

pub fn spawn_with(&mut self, options: SpawnOptions<'_>) -> Result<Child>

Spawns using one operation’s borrowed capabilities and policy.

§Errors

Returns validation, resource-acquisition, or process-creation errors.

Source

pub fn spawn_suspended(&mut self) -> Result<SuspendedChild>

Spawns in the suspended type state with default options.

§Errors

Returns validation, resource-acquisition, or process-creation errors.

Examples found in repository?
examples/suspended_inspection.rs (line 12)
4fn main() -> std::io::Result<()> {
5    use std::os::windows::io::AsHandle;
6
7    use windows_spawn::Command;
8
9    let mut command = Command::new(r"C:\Windows\System32\cmd.exe");
10    command.args(["/D", "/C", "exit /b 0"]);
11
12    let suspended = command.spawn_suspended()?;
13    println!("created suspended process {}", suspended.id());
14    let _process = suspended.as_handle();
15    let _primary_thread = suspended.primary_thread_handle();
16
17    let mut child = suspended.resume()?;
18    assert!(child.wait()?.success());
19    Ok(())
20}
Source

pub fn spawn_suspended_with( &mut self, options: SpawnOptions<'_>, ) -> Result<SuspendedChild>

Spawns in the suspended type state using explicit options.

§Errors

Returns validation, resource-acquisition, or process-creation errors.

Source

pub fn status(&mut self) -> Result<ExitStatus>

Runs the process and waits for its status using default options.

§Errors

Returns an error from spawning, waiting, or retrieving the exit code.

Examples found in repository?
examples/handle_handoff.rs (line 16)
4fn main() -> std::io::Result<()> {
5    use std::fs::File;
6
7    use windows_spawn::Command;
8
9    let log = File::create("worker.log")?;
10    let mut command = Command::new("worker.exe");
11    command.arg("--log-handle").arg_handle(&log)?;
12
13    // arg_handle stored a private non-inheritable duplicate. The worker
14    // protocol parses the following decimal argument as its borrowed handle.
15    drop(log);
16    let status = command.status()?;
17    assert!(status.success());
18    Ok(())
19}
Source

pub fn status_with(&mut self, options: SpawnOptions<'_>) -> Result<ExitStatus>

Runs the process and waits for its status using explicit options.

§Errors

Returns an error from spawning, waiting, or retrieving the exit code.

Source

pub fn output(&mut self) -> Result<Output>

Runs the process and captures output using default options.

§Errors

Returns an error from spawning, waiting, reading, or Job termination.

Source

pub fn output_with(&mut self, options: SpawnOptions<'_>) -> Result<Output>

Runs the process and captures output using explicit options.

§Errors

Returns an error from spawning, waiting, reading, or Job termination.

Examples found in repository?
examples/managed_output.rs (line 11)
4fn main() -> std::io::Result<()> {
5    use windows_spawn::{Command, DropPolicy, SpawnOptions};
6
7    let mut command = Command::new(r"C:\Windows\System32\cmd.exe");
8    command
9        .args(["/D", "/S", "/C"])
10        .raw_arg("echo managed output");
11    let output = command.output_with(SpawnOptions::new().drop_policy(DropPolicy::KillTree))?;
12
13    assert!(output.status.success());
14    print!("{}", String::from_utf8_lossy(&output.stdout));
15    Ok(())
16}

Trait Implementations§

Source§

impl Debug for Command

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.