proc_open

proc_open(array|string $command, array $descriptor_spec, array &$pipes, ?string $cwd = null, ?array $env_vars = null, ?array $options = null): resource|false

Spawns a child process with bidirectional pipes: descriptor_spec maps fd 0/1/2, $pipes receives PHP-side handles, proc_close reaps - the only exec-family function with two-way I/O.

C C23

C23
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    /* popen(3) is one-directional only; a true two-way pipe needs
       pipe(2) + fork(2) + execlp(3) by hand */
    int in_pipe[2], out_pipe[2];
    if (pipe(in_pipe) != 0 || pipe(out_pipe) != 0) return 1;
    pid_t pid = fork();
    if (pid == 0) {
        /* child: stdin <- in_pipe read end, stdout -> out_pipe write end */
        dup2(in_pipe[0], 0);
        dup2(out_pipe[1], 1);
        close(in_pipe[0]); close(in_pipe[1]);
        close(out_pipe[0]); close(out_pipe[1]);
        execlp("cat", "cat", (char *)NULL);
        _exit(127);
    }
    close(in_pipe[0]);
    close(out_pipe[1]);
    if (write(in_pipe[1], "pipe talk\n", 10) != 10) return 1;
    close(in_pipe[1]);
    char buf[64];
    ssize_t n = read(out_pipe[0], buf, sizeof buf - 1);
    if (n > 0) buf[n] = '\0'; else buf[0] = '\0';
    close(out_pipe[0]);
    int status = 0;
    waitpid(pid, &status, 0);
    fputs(buf, stdout);
    printf("exit code: %d\n", WEXITSTATUS(status));
    return 0;
}
Output
pipe talk
exit code: 0

C++ C++26

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

int main() {
    // popen(3) is one-directional by design: "r" reads stdout only, there is
    // no way to feed stdin - the classic limitation vs PHP's proc_open
    FILE *fp = popen("echo pipe talk", "r");
    if (fp == nullptr) return 1;
    char buf[64];
    while (fgets(buf, sizeof buf, fp) != nullptr) {
        std::cout << buf;
    }
    int status = pclose(fp);
    std::cout << "exit code: " << (status == 0 ? 0 : 1) << "\n";
    return 0;
}
Output
pipe talk
exit code: 0

C# v11.0.100

v11.0.100
// ProcessStartInfo with RedirectStandardInput/Output: bidirectional talk
using System.Diagnostics;

var psi = new ProcessStartInfo("cat")
{
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
};
using var proc = Process.Start(psi)!;
await proc.StandardInput.WriteAsync("pipe talk\n");
proc.StandardInput.Close();
string output = proc.StandardOutput.ReadToEnd();
Console.Write(output);
await proc.WaitForExitAsync();
Console.WriteLine("exit code: " + proc.ExitCode);
Output
pipe talk
exit code: 0

Go v1.27.4

v1.27.4
package main

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

func main() {
	// exec.Command + StdinPipe/StdoutPipe: bidirectional pipes to the child
	cmd := exec.Command("cat")
	stdin, err := cmd.StdinPipe()
	if err != nil {
		panic(err)
	}
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		panic(err)
	}
	if err := cmd.Start(); err != nil {
		panic(err)
	}
	stdin.Write([]byte("pipe talk\n"))
	stdin.Close()
	buf := make([]byte, 32)
	n, _ := stdout.Read(buf)
	fmt.Print(string(buf[:n]))
	if err := cmd.Wait(); err != nil {
		panic(err)
	}
	fmt.Println("exit code:", cmd.ProcessState.ExitCode())
	_ = os.Getpid
}
Output
pipe talk
exit code: 0

Java v27.0.1

v27.0.1
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        // ProcessBuilder: getOutputStream feeds the child stdin, getInputStream
        // reads its stdout - two directions, just like proc_open
        Process proc = new ProcessBuilder("cat").start();
        OutputStream in = proc.getOutputStream();
        in.write("pipe talk\n".getBytes());
        in.close(); // EOF for cat
        InputStream out = proc.getInputStream();
        byte[] buf = out.readAllBytes();
        System.out.print(new String(buf));
        System.out.println("exit code: " + proc.waitFor());
    }
}
Output
pipe talk
exit code: 0

JavaScript v26.13.1

v26.13.1
// child_process.spawn: stdio pipes give the same bidirectional talk
const { spawn } = require("child_process");
const child = spawn("cat", []);
child.stdin.write("pipe talk\n");
child.stdin.end();
child.stdout.on("data", (chunk) => process.stdout.write(chunk));
child.on("close", (code) => console.log("exit code:", code));
Output
pipe talk
exit code: 0

PHP v8.6.0

v8.6.0
// proc_open: array command (PHP 7.4+) runs without a shell; pipes talk
// both ways (0=stdin r, 1=stdout w)
$proc = proc_open(['cat'], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
var_dump(is_resource($proc));
fwrite($pipes[0], "pipe talk\n");
fclose($pipes[0]); // close our write end so cat sees EOF
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
echo 'exit code: ', proc_close($proc), "\n";
Output
bool(true)
pipe talk
exit code: 0

Python v3.15.2

v3.15.2
import subprocess

# subprocess.Popen with stdin/stdout pipes: talk to the child both ways
proc = subprocess.Popen(["cat"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
proc.stdin.write("pipe talk\n")
proc.stdin.close()
print(proc.stdout.read(), end="")
print("exit code:", proc.wait())
Output
pipe talk
exit code: 0

Rust v1.99.1

v1.99.1
use std::io::Read;
use std::io::Write;
use std::process::{Command, Stdio};

fn main() {
    // Command with piped stdin/stdout: take() hands the pipe handles over
    let mut child = Command::new("cat")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut stdin = child.stdin.take().unwrap();
    let mut stdout = child.stdout.take().unwrap();
    stdin.write_all(b"pipe talk\n").unwrap();
    drop(stdin); // close our end so cat sees EOF
    let mut buf = String::new();
    stdout.read_to_string(&mut buf).unwrap();
    print!("{buf}");
    let status = child.wait().unwrap();
    println!("exit code: {}", status.code().unwrap());
}
Output
pipe talk
exit code: 0

TypeScript v26.13.1

v26.13.1
// child_process.spawn: stdio pipes give the same bidirectional talk
import { spawn } from "child_process";
const child = spawn("cat", []);
child.stdin.write("pipe talk\n");
child.stdin.end();
child.stdout.on("data", (chunk: Buffer) => process.stdout.write(chunk));
child.on("close", (code: number | null) => console.log("exit code:", code));
Output
pipe talk
exit code: 0

Language differences

C: popen(3) has only one direction ("r" or "w", pick one) - two-way needs the full pipe(2)+fork(2)+dup2+execlp(3) hand-roll in this example; reap with waitpid+WEXITSTATUS.

C++: same popen limitation as C (this example shows one-way "r"); for two-way use pipe/fork by hand or boost::process.

C#: ProcessStartInfo booleans RedirectStandardInput/Output + StandardInput.WriteAsync/StandardOutput.ReadToEnd() - note the async events (OutputDataReceived) and synchronous ReadToEnd must not be mixed (deadlock).

Go: exec.Command + explicit StdinPipe()/StdoutPipe() handles; or cmd.Stdin = strings.NewReader(...) (io.Writer/Reader injection is more idiomatic).

Java: ProcessBuilder + getOutputStream() (feeds the child's stdin)/getInputStream() (reads its stdout) - named from the parent's view, famously confusing on first use.

JavaScript: child_process.spawn gives full duplex streams (pipeable); exec buffers into a callback (with a max buffer); spawn matches PHP's proc_open shape.

PHP: proc_open is the only bidirectional one in the exec/system/shell_exec/popen family - descriptor_spec maps 0/1/2 (and can open custom descriptors >2 to pass keys to co-processes, per the manual); an array command (PHP 7.4+) skips the shell with PHP handling escaping (manual-stated, safer cross-platform); returns a resource reaped by proc_close (an empty command array throws ValueError since PHP 8.3); proc_get_status inspects runtime state; proc_terminate kills. Windows note: Unix commands like cat are unavailable (this entry's demo command is cat, common to macOS/Linux; on Windows swap for findstr/PowerShell or skip).

Python: subprocess.Popen(stdin=PIPE, stdout=PIPE) is bidirectional; subprocess.run(input=...) is the one-shot convenience; communicate() prevents the classic deadlock of "pipe buffer full, both sides wait" (this example's text is too small to trigger).

Rust: Command::stdin(Stdio::piped()) + child.stdin.take().unwrap() (take extracts the Option handle); drop(stdin) closes our end for EOF - the ownership model makes pipe possession explicit.

TypeScript: same as JavaScript (spawn streams).