Code Example Template
Deep-Dive System Documentation
Spawning Operating System Processes
To write automation software or launch macro actions, you often need to spawn foreign executable binaries or interact with native OS shells directly. Rust handles this securely using std::process::Command.
Spawning Processes Asynchronously
To run a command and let it run in the background (non-blocking) without waiting for completion:
use std::process::Command;
Command::new("cmd")
.arg("/C")
.arg("start https://vercel.com")
.spawn() // Launches asynchronously in OS thread pool
.expect("Failed to execute launcher command");
Capturing Standard Output (Blocking)
To wait for a command to finish and extract its stdout/stderr streams:
let output = Command::new("git")
.arg("--version")
.output() // Blocks caller thread until process completes
.expect("failed to execute process");
let version_str = String::from_utf8_lossy(&output.stdout);
Security Note
Unlike languages that pass raw unescaped strings directly to the OS command processor, Command passes arguments as separated arguments to the OS API (CreateProcessW on Windows). This protects against command injection vulnerabilities by design.
Quick Reference Guide
use std::process::Command;
let output = Command::new("ls").output();