【远程工具】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 中与系统交互的重要工具之一。

相关推荐
Source.Liu6 小时前
【time-rs】月份枚举实现
rust·time
福大大架构师每日一题8 小时前
2025年12月TIOBE编程语言排行榜,Go语言排名第15,Rust语言排名17。编程语言 R 重返前十。
开发语言·后端·rust
苏 凉9 小时前
在 openEuler 24.03 LTS SP2 上安装部署 iSula 容器引擎及性能测试
开发语言·rust
ULTRA??10 小时前
字符串处理小写字母转换大写字母
c++·python·rust
ZC·Shou1 天前
Rust 之二 各组件工具的源码、构建、配置、使用(二)
开发语言·ide·rust·工具·命令·clippy·rustfmt
ULTRA??1 天前
Rust的移动语义
c++·算法·rust
熬了夜的程序员1 天前
【Rust学习之路】序
开发语言·后端·学习·rust
Mintopia1 天前
⚙️ 模型接口与微调兼容性:AIGC系统整合的底层心脏跳动
人工智能·架构·rust
ULTRA??1 天前
RUST是移动语义与copy trait
算法·rust
Source.Liu1 天前
【time-rs】编译器优化提示模块详解
rust·time