std/process

std/process 模組提供了一個高階 API,用於衍生(spawning)子行程、執行系統指令並捕捉其輸出。

概覽

使用方法

import "std/process.zc"
import "std/io.zc"

fn main() {
    // 基本指令執行
    let output = Command::new("echo")
        .arg("hello world")
        .output();
        
    if (output.exit_code == 0) {
        println(f"捕捉到內容: {output.std_out}");
        // output.std_out 是一個 String,會自動釋放
    } else {
        println(f"指令失敗,結束代碼為 {output.exit_code}");
    }
}

結構體定義

Command

用於配置和衍生行程的生成器。

struct Command {
    program: String;
    args: Vec<String>;
}

Output

已完成行程執行的結果。

struct Output {
    std_out: String;
    exit_code: int;
}

方法

Command 方法

方法簽名說明
newCommand::new(program: char*) -> Command為指定程式建立一個新的 Command。
argarg(self, arg: char*) -> Command*添加一個參數並返回指向自身的指標以進行鏈式調用。
outputoutput(self) -> Output執行指令並等待完成,同時捕捉標準輸出。
statusstatus(self) -> int執行指令並返回結束狀態代碼。

記憶體管理

方法簽名說明
freefree(self)手動釋放內部指令指令緩衝區。
Traitimpl Drop for Command自動清理指令緩衝區。
Traitimpl Drop for Output自動釋放已捕捉的輸出字串。