exec

exec(string $command, array &$output = null, int &$result_code = null): string|false

执行外部命令并捕获输出(经 shell,返回最后一行)。

C C23

C23
#include <stdio.h>

int main(void) {
    /* popen 是 system() 的捕获搭档:读取 shell 命令的 stdout */
    FILE *fp = popen("echo hello exec", "r");
    char buf[64];
    while (fgets(buf, sizeof buf, fp)) printf("%s", buf);
    pclose(fp);
    return 0;
}
输出
hello exec

C++ C++26

C++26
#include <cstdio>

int main() {
    // popen 捕获 shell 命令的 stdout(标准库没有 exec 搭档)
    FILE *fp = popen("echo hello exec", "r");
    char buf[64];
    while (fgets(buf, sizeof buf, fp)) std::printf("%s", buf);
    pclose(fp);
    return 0;
}
输出
hello exec

C# v11.0.100

v11.0.100
using System.Diagnostics;

var psi = new ProcessStartInfo("echo");
psi.ArgumentList.Add("hello"); // ArgumentList 传参数组,不拼 shell 字符串
psi.ArgumentList.Add("exec");
psi.RedirectStandardOutput = true;
var p = Process.Start(psi)!;
Console.WriteLine(p.StandardOutput.ReadToEnd().Trim());
p.WaitForExit();
输出
hello exec

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os/exec"
)

func main() {
	// exec.Command 接收参数数组,绝不拼 shell 字符串
	out, _ := exec.Command("echo", "hello", "exec").Output()
	fmt.Print(string(out))
}
输出
hello exec

Java v27.0.1

v27.0.1
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        // ProcessBuilder:基于参数数组,shell 从不参与
        Process p = new ProcessBuilder(List.of("echo", "hello", "exec")).start();
        try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            System.out.println(r.readLine()); // 类似 exec 的返回值:最后一行
        }
        System.out.println(p.waitFor()); // 类似 exec 的 $result_code
    }
}
输出
hello exec
0

JavaScript v26.13.1

v26.13.1
const { execSync } = require("node:child_process");
// execSync 走 shell,与 PHP exec 语义对应(返回 Buffer)
const out = execSync("echo hello exec");
console.log(out.toString().trim());
输出
hello exec

PHP v8.6.0

v8.6.0
$out = [];
$last = exec('echo hello exec', $out, $code); // 经 shell 执行;$out 收集全部 stdout 行
echo $last, PHP_EOL;   // 返回值 = 最后一行
echo $out[0], PHP_EOL; // $output = 每一行
echo $code, PHP_EOL;   // 命令退出状态
输出
hello exec
hello exec
0

Python v3.15.2

v3.15.2
import subprocess

# 参数列表:shell 从不参与
r = subprocess.run(["echo", "hello", "exec"], capture_output=True, text=True)
print(r.stdout.strip())
print(r.returncode)
输出
hello exec
0

Rust v1.99.1

v1.99.1
use std::process::Command;

fn main() {
    // .arg() 构造参数数组:没有 shell 字符串,没有注入面
    let out = Command::new("echo").arg("hello").arg("exec").output().unwrap();
    print!("{}", String::from_utf8_lossy(&out.stdout));
}
输出
hello exec

TypeScript v26.13.1

v26.13.1
import { execFileSync } from "node:child_process";
// execFileSync 绕开 shell:参数数组进,stdout 出(安全默认)
const out: string = execFileSync("echo", ["hello", "exec"]).toString();
console.log(out.trim());
输出
hello exec

语言差异说明

C:标准库没有进程 API——POSIX popen/pclose 捕获 shell 命令 stdout(示例),底层由 fork/exec 加管道实现;命令字符串拼接就是注入入口。

C++:同 C 的 popen(示例);C++17 标准库仍无进程 API。

C#:System.Diagnostics.Process + ArgumentList 传参数组(示例)——不经过 shell、无引号转义问题;拼接 Arguments 字符串才是注入入口。

Go:os/exec.Command 一律参数数组(示例),根本不调用 shell——只有显式 exec.Command("sh", "-c", cmd) 才引入 shell 与注入面。

Java:ProcessBuilder 同样参数数组直达 exec(示例);需要 shell 语义时才显式 new ProcessBuilder("sh", "-c", cmd),此时才谈转义。

JavaScript:execSync/exec 走 shell(与 PHP exec 同语义,示例);安全姿势是 execFileSync/spawnSync 参数数组(见 escapeshellarg 条)。

PHP:exec 语义 = 经 shell 执行 + 返回最后一行;$output 逐行收集、$result_code 收退出码(示例)。参数含用户输入时必须 escapeshellarg 或改走参数化方案。

Python:subprocess.run 传列表默认不经 shell(示例);shell=True 才引入 shell——官方文档第一条警告就是永不拼接 shell 字符串。

Rust:std::process::Command 参数数组(示例),不经 shell;等价 shell 语义需显式 Command::new("sh").arg("-c").arg(cmd)。

TypeScript:同 JavaScript;Node 官方建议优先 execFile 系列,shell 变体仅用于确需管道/通配符的场景。