shell_exec

shell_exec(string $command): string|false|null

经 shell 执行命令并返回完整输出字符串(等价反引号语法)。

C C23

C23
#include <stdio.h>
#include <string.h>

int main(void) {
    /* 把整条流读进一个缓冲区:shell_exec 返回全部输出 */
    FILE *fp = popen("echo hello shell_exec", "r");
    char all[256] = "";
    char buf[64];
    while (fgets(buf, sizeof buf, fp)) strcat(all, buf);
    pclose(fp);
    all[strcspn(all, "\n")] = '\0'; /* 去掉尾部换行 */
    printf("%s\n", all);
    return 0;
}
输出
hello shell_exec

C++ C++26

C++26
#include <cstdio>
#include <iostream>
#include <string>

int main() {
    // 把整条流累积进一个字符串,对应 shell_exec
    FILE *fp = popen("echo hello shell_exec", "r");
    std::string all;
    char buf[64];
    while (fgets(buf, sizeof buf, fp)) all += buf;
    pclose(fp);
    while (!all.empty() && (all.back() == '\n' || all.back() == '\r')) all.pop_back();
    std::cout << all << "\n";
    return 0;
}
输出
hello shell_exec

C# v11.0.100

v11.0.100
using System.Diagnostics;

var psi = new ProcessStartInfo("echo");
psi.ArgumentList.Add("hello");
psi.ArgumentList.Add("shell_exec");
psi.RedirectStandardOutput = true;
var p = Process.Start(psi)!;
// ReadToEnd 一次性读全 stdout,对应 shell_exec
Console.WriteLine(p.StandardOutput.ReadToEnd().Trim());
p.WaitForExit();
输出
hello shell_exec

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os/exec"
	"strings"
)

func main() {
	// Output() 把整个 stdout 缓冲成一个切片,对应 shell_exec
	out, _ := exec.Command("echo", "hello", "shell_exec").Output()
	fmt.Println(strings.TrimSpace(string(out)))
}
输出
hello shell_exec

Java v27.0.1

v27.0.1
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws Exception {
        // readAllBytes 缓冲整个 stdout,对应 shell_exec 的返回值
        Process p = new ProcessBuilder("echo", "hello", "shell_exec").start();
        String out = new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
        System.out.println(out.trim());
        p.waitFor();
    }
}
输出
hello shell_exec

JavaScript v26.13.1

v26.13.1
const { execSync } = require("node:child_process");
// execSync 把整个 stdout 缓冲成 Buffer 并返回,对应 shell_exec
const out = execSync("echo hello shell_exec");
console.log(out.toString().trim());
输出
hello shell_exec

PHP v8.6.0

v8.6.0
// shell_exec 返回完整 stdout(反引号语法为其别名,PHP 8.5 起弃用),失败返回 null
$out = shell_exec('echo hello shell_exec');
echo trim($out), PHP_EOL;
输出
hello shell_exec

Python v3.15.2

v3.15.2
import subprocess

# check_output 捕获完整 stdout 并返回,对应 shell_exec
out = subprocess.check_output(["echo", "hello", "shell_exec"], text=True)
print(out.strip())
输出
hello shell_exec

Rust v1.99.1

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

fn main() {
    // .output() 缓冲整个 stdout,对应 shell_exec
    let out = Command::new("echo").arg("hello").arg("shell_exec").output().unwrap();
    println!("{}", String::from_utf8_lossy(&out.stdout).trim());
}
输出
hello shell_exec

TypeScript v26.13.1

v26.13.1
import { execSync } from "node:child_process";
// execSync 缓冲整个 stdout 并返回,对应 shell_exec
const out: string = execSync("echo hello shell_exec").toString();
console.log(out.trim());
输出
hello shell_exec

语言差异说明

C:无返回完整输出的标准 API——popen 逐块读入再拼成整串(示例);失败信号只有 pclose 返回值,需自己区分空输出与失败。

C++:同 C 的 popen + string 累积(示例);C++17 仍无进程 API,第三方 boost::process 才有完整的管道抽象。

C#:RedirectStandardOutput + ReadToEnd 就是「一次拿全」(示例);注意 ReadToEnd 在 stdout 与 stderr 都要读时可能死锁,需异步读其一。

Go:Output() 把 stdout 缓冲成一个字节切片(示例),并把 stderr 接到父进程;想要全拿 stderr 用 CombinedOutput()——连错误流一起返回,更像 shell_exec 的行为。

Java:readAllBytes 一次读全 stdout(示例);getErrorStream 单独读错误流——两流都要全收时各读各的,避免管道填满阻塞。

JavaScript:execSync 返回完整 stdout(示例,走 shell 同 PHP 语义);超时与非 0 退出直接抛异常,try/catch 里的 e.stdout 才是部分输出。

PHP:shell_exec 与反引号 $out = \cmd\ 同义(反引号自 PHP 8.5 起弃用),返回完整输出字符串;失败返回 null(PHP 7+ 某些错误为 false)——示例用 trim 去掉命令自带的尾部换行。

Python:check_output 捕获完整 stdout 并返回(示例);非 0 退出抛 CalledProcessError(e.output 携带部分输出);要连 stderr 一起收则加 stderr=subprocess.STDOUT。

Rust:.output() 返回 Output 结构:stdout/stderr 分字段、status 独立(示例)——比 shell_exec 更结构化,失败不抛错而是看 status.success()。

TypeScript:同 JavaScript;execSync 的返回类型随 encoding 参数变化,{ encoding: "buffer" } 可拿到原始 Buffer。