exec

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

Executes an external command and captures its output (via the shell, returning the last line).

C C23

C23
#include <stdio.h>

int main(void) {
    /* popen is the capture pair of system(): read the shell command's stdout */
    FILE *fp = popen("echo hello exec", "r");
    char buf[64];
    while (fgets(buf, sizeof buf, fp)) printf("%s", buf);
    pclose(fp);
    return 0;
}
Output
hello exec

C++ C++26

C++26
#include <cstdio>

int main() {
    // popen captures a shell command's stdout (the standard library has no exec pair)
    FILE *fp = popen("echo hello exec", "r");
    char buf[64];
    while (fgets(buf, sizeof buf, fp)) std::printf("%s", buf);
    pclose(fp);
    return 0;
}
Output
hello exec

C# v11.0.100

v11.0.100
using System.Diagnostics;

var psi = new ProcessStartInfo("echo");
psi.ArgumentList.Add("hello"); // ArgumentList: pass argv, no shell string concat
psi.ArgumentList.Add("exec");
psi.RedirectStandardOutput = true;
var p = Process.Start(psi)!;
Console.WriteLine(p.StandardOutput.ReadToEnd().Trim());
p.WaitForExit();
Output
hello exec

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os/exec"
)

func main() {
	// exec.Command takes an argument array; never build a shell string
	out, _ := exec.Command("echo", "hello", "exec").Output()
	fmt.Print(string(out))
}
Output
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: argv-based, the shell is never involved
        Process p = new ProcessBuilder(List.of("echo", "hello", "exec")).start();
        try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            System.out.println(r.readLine()); // like exec's return value: the last line
        }
        System.out.println(p.waitFor()); // like exec's $result_code
    }
}
Output
hello exec
0

JavaScript v26.13.1

v26.13.1
const { execSync } = require("node:child_process");
// execSync goes through the shell, mirroring PHP's exec semantics (returns a Buffer)
const out = execSync("echo hello exec");
console.log(out.toString().trim());
Output
hello exec

PHP v8.6.0

v8.6.0
$out = [];
$last = exec('echo hello exec', $out, $code); // runs via the shell; $out collects all stdout lines
echo $last, PHP_EOL;   // return value = the LAST line
echo $out[0], PHP_EOL; // $output = every line
echo $code, PHP_EOL;   // exit status of the command
Output
hello exec
hello exec
0

Python v3.15.2

v3.15.2
import subprocess

# argument list: the shell is never involved
r = subprocess.run(["echo", "hello", "exec"], capture_output=True, text=True)
print(r.stdout.strip())
print(r.returncode)
Output
hello exec
0

Rust v1.99.1

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

fn main() {
    // .arg() builds an argv; no shell string, no injection surface
    let out = Command::new("echo").arg("hello").arg("exec").output().unwrap();
    print!("{}", String::from_utf8_lossy(&out.stdout));
}
Output
hello exec

TypeScript v26.13.1

v26.13.1
import { execFileSync } from "node:child_process";
// execFileSync skips the shell: argv in, stdout out (the safe default)
const out: string = execFileSync("echo", ["hello", "exec"]).toString();
console.log(out.trim());
Output
hello exec

Language differences

C: the standard library has no process API — POSIX popen/pclose capture a shell command's stdout (example), implemented via fork/exec plus a pipe; concatenating the command string is exactly the injection doorway.

C++: the same popen as C (example); the C++17 standard library still has no process API.

C#: System.Diagnostics.Process + ArgumentList passes an argument array (example) — no shell involved, no quoting issues; concatenating the Arguments string is what creates the injection doorway.

Go: os/exec.Command always takes an argument array (example) and never invokes a shell — only an explicit exec.Command("sh", "-c", cmd) introduces a shell and an injection surface.

Java: ProcessBuilder likewise goes straight to exec with an argv (example); you opt into shell semantics explicitly with new ProcessBuilder("sh", "-c", cmd), and only then does escaping matter.

JavaScript: execSync/exec go through the shell (same semantics as PHP's exec, example); the safe pattern is execFileSync/spawnSync with an argument array (see the escapeshellarg entry).

PHP: exec means run-via-shell and return the last line; $output collects lines, $result_code collects the exit status (example). When parameters contain user input, escapeshellarg them or switch to a parameterized approach.

Python: subprocess.run with a list does not use the shell (example); shell=True is what brings the shell in — the docs' first warning is never to concatenate shell strings.

Rust: std::process::Command takes an argument array (example), no shell; shell semantics require an explicit Command::new("sh").arg("-c").arg(cmd).

TypeScript: same as JavaScript; Node's guidance prefers the execFile family, reserving the shell variants for cases that truly need pipes or globbing.