# std::process

啟動並控制外部程式，以及結束目前的程式並回報結束碼。

## 這個模組做什麼

有時候最快的做法是直接呼叫系統上現成的工具：跑 `git` 查版本、呼叫壓縮程式、執行一段 shell 指令。`std::process` 的 `Command` 就是 Rust 版的「在終端機打指令」，而且能拿到輸出、餵入資料、檢查成功與否。

另一半功能是控制**自己**怎麼結束：`process::exit` 立即終止，`ExitCode` 讓 `main` 回傳結束碼給呼叫者（shell、CI 系統）。

| 需求 | 用什麼 |
| --- | --- |
| 執行並取得全部輸出 | `Command::output()` |
| 執行並只看成功與否（輸出直接顯示） | `Command::status()` |
| 邊跑邊互動、串接管線 | `Command::spawn()` + `Stdio::piped()` |
| 立即結束程式 | `process::exit(code)` |
| 讓 `main` 回傳結束碼 | `ExitCode` |

## 匯入

```rust
use std::process::{self, Command, ExitCode, Stdio};
```

本頁範例呼叫 `echo`、`printf`、`printenv`、`sort`、`wc`、`sh`、`true`、`false`，在 macOS 與 Linux 都有。Windows 沒有這些獨立程式（`echo` 是 `cmd.exe` 的內建指令），要寫成 `Command::new("cmd").args(["/C", "echo hello"])`。

## 常用 API

### Command::new 與 output：執行並收集輸出

`Command::new` 指定要執行的程式，`arg`／`args` 加上參數，最後呼叫 `output()`：它會等程式跑完，把標準輸出、標準錯誤收集成 `Vec<u8>`，連同結束狀態一起放在 `Output` 裡。

`Command` 不經過 shell，參數直接交給程式，所以不需要處理引號跳脫，也不會被 shell 解讀 `*`、`$` 這些特殊字元。

簽名：

```rust
pub fn new<S: AsRef<OsStr>>(program: S) -> Command;
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command;
pub fn output(&mut self) -> io::Result<Output>;
```

注意：`output()` 回傳 `Ok` 只代表程式**成功啟動並結束**，不代表它執行成功；要另外檢查 `out.status.success()`。輸出是位元組，轉文字用 `String::from_utf8_lossy`。

範例：

```rust
use std::process::Command;

fn main() -> std::io::Result<()> {
    let out = Command::new("echo").arg("hello from child").output()?;
    println!("success: {}", out.status.success());
    println!("stdout: {:?}", String::from_utf8_lossy(&out.stdout));
    println!("stderr bytes: {}", out.stderr.len());
    Ok(())
}
```

輸出：

```text
success: true
stdout: "hello from child\n"
stderr bytes: 0
```

### status：只取得結束狀態

`status()` 執行程式並等待結束，子程式的輸出直接顯示在終端機，回傳 `ExitStatus`。`success()` 判斷結束碼是否為 0，`code()` 取得結束碼；被訊號（signal）終止的程式沒有結束碼，`code()` 回傳 `None`。

簽名：

```rust
pub fn status(&mut self) -> io::Result<ExitStatus>;
pub fn success(&self) -> bool;
pub fn code(&self) -> Option<i32>;
```

範例：

```rust
use std::process::Command;

fn main() -> std::io::Result<()> {
    for prog in ["true", "false"] {
        let status = Command::new(prog).status()?;
        println!("{:<5} success={} code={:?}", prog, status.success(), status.code());
    }

    let st = Command::new("sh").args(["-c", "exit 7"]).status()?;
    println!("sh exit 7 -> {:?}", st.code());
    Ok(())
}
```

輸出：

```text
true  success=true code=Some(0)
false success=false code=Some(1)
sh exit 7 -> Some(7)
```

### args 與 env：參數與環境變數

`args` 一次加入多個參數；`env` 替子程式設定環境變數，`env_clear` 清空所有繼承來的環境變數，`current_dir` 指定子程式的工作目錄。這些設定只影響子程式，不會改到目前程式自己的環境。

簽名：

```rust
pub fn args<I, S>(&mut self, args: I) -> &mut Command
where I: IntoIterator<Item = S>, S: AsRef<OsStr>;
pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command;
pub fn env_clear(&mut self) -> &mut Command;
```

注意：`env_clear` 也會清掉 `PATH`，之後若程式名稱不是絕對路徑，在某些平台上可能找不到。範例中 `printenv` 找不到變數時以非 0 結束碼離開，所以 `success` 是 `false`。

範例：

```rust
use std::process::Command;

fn main() -> std::io::Result<()> {
    let out = Command::new("printf")
        .args(["%s=%s\n", "name", "Rust 新手"])
        .output()?;
    print!("{}", String::from_utf8_lossy(&out.stdout));

    let out = Command::new("printenv")
        .arg("GREETING")
        .env("GREETING", "hi there")
        .output()?;
    print!("{}", String::from_utf8_lossy(&out.stdout));

    let out = Command::new("printenv")
        .arg("GREETING")
        .env_clear()
        .output()?;
    println!("after env_clear: success={}", out.status.success());
    Ok(())
}
```

輸出：

```text
name=Rust 新手
hi there
after env_clear: success=false
```

### spawn 與 Stdio::piped：管線與互動

`spawn()` 啟動程式後立刻返回一個 `Child`，不等它結束。搭配 `Stdio::piped()`，就能從 `child.stdin` 寫入資料、從 `child.stdout` 讀出結果。`wait_with_output()` 等程式結束並收集剩餘輸出。

把一個子程式的 `stdout` 轉成 `Stdio` 交給下一個子程式的 `stdin`，就等同 shell 的 `printf ... | wc -l`。

簽名：

```rust
pub fn spawn(&mut self) -> io::Result<Child>;
pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command;
pub fn wait_with_output(self) -> io::Result<Output>;
```

注意：寫完 stdin 後要讓它被 drop（範例用大括號區塊），子程式才會收到 EOF；否則像 `sort` 這種要讀完才輸出的程式會一直等，造成死結。`spawn` 出來的 `Child` 被 drop 時**不會**終止子程式，也不會等它，記得 `wait`。

範例：

```rust
use std::io::Write;
use std::process::{Command, Stdio};

fn main() -> std::io::Result<()> {
    let mut child = Command::new("sort")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()?;

    {
        let mut stdin = child.stdin.take().expect("stdin is piped");
        stdin.write_all(b"pear\napple\nfig\n")?;
    }

    let out = child.wait_with_output()?;
    print!("{}", String::from_utf8_lossy(&out.stdout));

    let producer = Command::new("printf")
        .arg("one\ntwo\nthree\n")
        .stdout(Stdio::piped())
        .spawn()?;
    let counter = Command::new("wc")
        .arg("-l")
        .stdin(Stdio::from(producer.stdout.expect("stdout is piped")))
        .output()?;
    println!("lines: {}", String::from_utf8_lossy(&counter.stdout).trim());
    Ok(())
}
```

輸出：

```text
apple
fig
pear
lines: 3
```

### 找不到程式：處理啟動失敗

程式不存在或沒有執行權限時，`output()`／`status()`／`spawn()` 直接回傳 `Err`，種類通常是 `ErrorKind::NotFound`。這和「程式有跑起來但回報失敗」是兩件事，要分開處理。

簽名：

```rust
pub fn output(&mut self) -> io::Result<Output>;
```

範例：

```rust
use std::io::ErrorKind;
use std::process::Command;

fn main() {
    match Command::new("this-command-does-not-exist").output() {
        Ok(out) => println!("ran: {}", out.status),
        Err(e) if e.kind() == ErrorKind::NotFound => println!("program not found"),
        Err(e) => println!("spawn failed: {}", e),
    }
}
```

輸出：

```text
program not found
```

### exit：立即結束程式

`process::exit(code)` 立刻結束整個行程，並把結束碼交給作業系統。它的回傳型別是 `!`（never type），代表永遠不會返回。

下面的範例輸出包含標準輸出與標準錯誤（`fatal: ...` 來自 `eprintln!`），結束碼是 2，可用 shell 的 `echo $?` 查看。

簽名：

```rust
pub fn exit(code: i32) -> !;
```

注意：`exit` 不會執行任何解構子（`Drop`），範例中的 `guard dropped` 沒有印出；`BufWriter` 裡尚未 flush 的資料也會遺失。除非真的需要從深處立即中止，否則優先讓 `main` 回傳 `ExitCode`。

範例：

```rust
use std::process;

struct Guard;

impl Drop for Guard {
    fn drop(&mut self) {
        println!("guard dropped");
    }
}

fn check(ok: bool) {
    if !ok {
        eprintln!("fatal: config missing");
        process::exit(2);
    }
}

fn main() {
    let _g = Guard;
    println!("checking...");
    check(false);
    println!("never printed");
}
```

輸出：

```text
checking...
fatal: config missing
```

### ExitCode：從 main 回傳結束碼

`main` 可以回傳 `ExitCode`，程式正常結束、解構子照常執行，最後把結束碼交給作業系統。`ExitCode::SUCCESS` 是 0，`ExitCode::FAILURE` 是 1，`ExitCode::from(u8)` 指定其他值。`main` 回傳 `Result<(), E>` 時，`Err` 會印出錯誤並以 1 結束，也是常見寫法。

下面的範例結束碼是 3，輸出來自標準錯誤。

簽名：

```rust
pub const SUCCESS: ExitCode;
pub const FAILURE: ExitCode;
impl From<u8> for ExitCode;
```

範例：

```rust
use std::process::ExitCode;

fn run(input: &str) -> Result<i32, String> {
    input.parse::<i32>().map_err(|e| format!("cannot parse {:?}: {}", input, e))
}

fn main() -> ExitCode {
    match run("forty-two") {
        Ok(n) => {
            println!("value = {}", n);
            ExitCode::SUCCESS
        }
        Err(msg) => {
            eprintln!("error: {}", msg);
            ExitCode::from(3)
        }
    }
}
```

輸出：

```text
error: cannot parse "forty-two": invalid digit found in string
```

## 重點整理

- `Command` 不經過 shell，參數不需要跳脫；需要 shell 功能時明確呼叫 `sh -c`
- `output()` 收集輸出、`status()` 只看結果、`spawn()` 用於管線與互動
- `Ok(output)` 不等於成功，還要檢查 `status.success()`
- 管線寫完 stdin 要 drop 它，否則子程式等不到 EOF
- `process::exit` 不執行 `Drop`；一般情況讓 `main` 回傳 `ExitCode`
