【远程工具】0 std::process::Command 介绍

std::process::Command 是 Rust 标准库中用于创建和配置子进程的主要类型。它允许你启动新的进程、设置其参数和环境变量、重定向输入/输出等。

基本用法

rust 复制代码
use std::process::Command;

let output = Command::new("echo")
    .arg("Hello, world!")
    .output()
    .expect("Failed to execute command");

println!("{}", String::from_utf8_lossy(&output.stdout));

主要功能

  1. 创建命令:
  • Command::new("可执行文件路径") - 创建一个新的命令构建器
  1. 添加参数:
  • .arg("参数") - 添加单个参数

  • .args(&["参数1", "参数2"]) - 添加多个参数

  1. 执行命令:
  • .output() - 执行命令并等待完成,收集所有输出

  • .status() - 执行命令并等待完成,返回退出状态

  • .spawn() - 启动命令并返回子进程句柄,不等待完成

  1. 环境配置:
  • .env("KEY", "value") - 设置环境变量

  • .env_remove("KEY") - 移除环境变量

  • .env_clear() - 清除所有环境变量

  1. 工作目录:
  • .current_dir("路径") - 设置子进程的工作目录
  1. 输入/输出重定向:
  • .stdin(Stdio::piped()) - 重定向标准输入

  • .stdout(Stdio::piped()) - 重定向标准输出

  • .stderr(Stdio::piped()) - 重定向标准错误

示例

执行命令并获取输出
rust 复制代码
let output = Command::new("ls")
    .arg("-l")
    .arg("-a")
    .output()
    .expect("ls command failed to start");
管道输入
rust 复制代码
use std::process::{Command, Stdio};

let mut child = Command::new("grep")
    .arg("hello")
    .stdin(Stdio::piped())
    .stdout(Stdio::piped())
    .spawn()
    .expect("failed to spawn child");

let mut stdin = child.stdin.take().expect("failed to get stdin");
std::thread::spawn(move || {
    stdin.write_all("hello world\ngoodbye\n".as_bytes()).expect("failed to write to stdin");
});

let output = child.wait_with_output().expect("failed to wait on child");
错误处理
rust 复制代码
match Command::new("nonexistent_command").output() {
    Ok(output) => {
        // 处理成功情况
    }
    Err(e) => {
        eprintln!("执行命令失败: {}", e);
    }
}
安全注意事项
  • Command 会继承父进程的环境变量,这可能带来安全风险

  • 构建命令时,参数应该来自可信源或经过适当转义

  • 在 Windows 上,参数传递的行为可能与 Unix 系统不同

Command 提供了强大而灵活的子进程管理功能,是 Rust 中与系统交互的重要工具之一。

相关推荐
Mr -老鬼17 分钟前
Rust适合干什么?为什么需要Rust?
开发语言·后端·rust
Mr -老鬼39 分钟前
Rust与Go:从学习到实战的全方位对比
学习·golang·rust
superman超哥3 小时前
Context与任务上下文传递:Rust异步编程的信息高速公路
开发语言·rust·编程语言·context与任务上下文传递·rust异步编程
古城小栈4 小时前
Rust 已经自举,却仍需GNU与MSVC工具链的缘由
开发语言·rust
古城小栈14 小时前
Rust 迭代器产出的引用层数——分水岭
开发语言·rust
peterfei19 小时前
IfAI v0.2.8 技术深度解析:从"工具"到"平台"的架构演进
rust·ai编程
栈与堆1 天前
LeetCode-1-两数之和
java·数据结构·后端·python·算法·leetcode·rust
superman超哥1 天前
双端迭代器(DoubleEndedIterator):Rust双向遍历的优雅实现
开发语言·后端·rust·双端迭代器·rust双向遍历
福大大架构师每日一题1 天前
2026年1月TIOBE编程语言排行榜,Go语言排名第16,Rust语言排名13。C# 当选 2025 年度编程语言。
golang·rust·c#
superman超哥1 天前
精确大小迭代器(ExactSizeIterator):Rust性能优化的隐藏利器
开发语言·后端·rust·编程语言·rust性能优化·精确大小迭代器