popen / pclose
popen(string $command, string $mode): resource|false — pclose(resource $handle): int
One-way process pipes: popen opens a unidirectional pipe to a child process ("r" reads its stdout, "w" writes to its stdin) whose pointer works with fgets/fwrite; pclose closes the pipe, reaps the child and returns its termination status — the direct descendant of Unix popen(3), complementing proc_open's two-way pipes.
C C23
#include <stdio.h>
int main(void) {
/* popen/pclose are the POSIX originals PHP's pair is named after. */
FILE *fp = popen("echo codeabc-stream", "r");
char buf[64];
while (fgets(buf, sizeof buf, fp)) {
fputs(buf, stdout);
}
int status = pclose(fp); // close the pipe and reap the child
printf("exit=%d\n", status);
return 0;
}
codeabc-stream exit=0
C++ C++26
#include <cstdio>
#include <iostream>
int main() {
// C++ has no standard process API: the POSIX popen/pclose pair
// is used verbatim.
FILE *fp = popen("echo codeabc-stream", "r");
char buf[64];
while (fgets(buf, sizeof buf, fp)) {
std::cout << buf;
}
int status = pclose(fp);
std::cout << "exit=" << status << '\n';
return 0;
}
codeabc-stream exit=0
C# v11.0.100
using System.Diagnostics;
// RedirectStandardOutput is the .NET equivalent of popen(..., "r").
using Process p = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "echo",
Arguments = "codeabc-stream",
RedirectStandardOutput = true,
UseShellExecute = false, // no shell: exec echo directly
},
};
p.Start();
Console.Write(p.StandardOutput.ReadToEnd());
p.WaitForExit();
Console.WriteLine($"exit={p.ExitCode}");
codeabc-stream exit=0
Go v1.27.4
package main
import (
"fmt"
"os/exec"
)
func main() {
// exec.Command().Output() is the one-shot pipe read;
// StdoutPipe() gives the streaming variant.
out, err := exec.Command("echo", "codeabc-stream").Output()
if err != nil {
panic(err)
}
fmt.Print(string(out))
fmt.Println("exit=0") // nil error means exit status 0
}
codeabc-stream exit=0
Java v27.0.1
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws Exception {
// ProcessBuilder is the modern API (Runtime.exec is legacy).
Process p = new ProcessBuilder("echo", "codeabc-stream").start();
InputStream in = p.getInputStream();
String out = new String(in.readAllBytes(), StandardCharsets.US_ASCII);
System.out.print(out);
System.out.println("exit=" + p.waitFor());
}
}
codeabc-stream exit=0
JavaScript v26.13.1
const { execSync } = require('node:child_process');
// execSync runs the command through /bin/sh and returns the stdout
// bytes; a non-zero exit would throw, so reaching the print means 0.
const out = execSync('echo codeabc-stream');
process.stdout.write(out.toString());
console.log('exit=0');
codeabc-stream exit=0
PHP v8.6.0
$fp = popen('echo codeabc-stream', 'r'); // one-way: read the child's stdout
echo fread($fp, 1024);
echo 'exit=', pclose($fp), "\n"; // close the pipe and reap the child
codeabc-stream exit=0
Python v3.15.2
import subprocess
# Popen(..., stdout=PIPE) is the exact popen("r") counterpart;
# communicate() reads to EOF and reaps the child.
p = subprocess.Popen(["echo", "codeabc-stream"], stdout=subprocess.PIPE)
out, _ = p.communicate()
print(out.decode(), end="")
print(f"exit={p.returncode}")
codeabc-stream exit=0
Rust v1.99.1
use std::process::Command;
fn main() {
// Command::output() is the one-shot pipe read;
// stdout(Stdio::piped()) is the streaming variant.
let out = Command::new("echo")
.arg("codeabc-stream")
.output()
.expect("spawn echo");
print!("{}", String::from_utf8_lossy(&out.stdout));
println!("exit={}", out.status.code().unwrap());
}
codeabc-stream exit=0
TypeScript v26.13.1
import { execSync } from 'node:child_process';
// execSync runs the command through /bin/sh and returns the stdout
// bytes; a non-zero exit would throw, so reaching the print means 0.
const out: Buffer = execSync('echo codeabc-stream');
process.stdout.write(out.toString());
console.log('exit=0');
codeabc-stream exit=0
Language differences
PHP: popen($cmd, 'r'|'w') opens a one-way pipe — 'r' reads the child's stdout, 'w' writes to its stdin; the returned pointer works with fgets/fread/fwrite; pclose() must close the pipe and reap the child, returning its termination status (undefined if PHP is built with --enable-sigchild, manual Note).
Division of labour with proc_open: reach for proc_open (a dedicated entry) when you need two-way pipes (stdin and stdout at once) or several independent pipes; popen covers a single direction and is the direct descendant of Unix popen(3).
Command interpretation and errors: $command runs through the shell (redirect, e.g. 2>&1, to capture stderr — the manual's own example); if the command does not exist a valid resource is still returned — read the error message out of the pipe (manual).
C: the namesake ancestors (POSIX, not ISO C); the example mirrors PHP's; pclose is internally waitpid(3) (manual pclose note).
C++: no process API in std — call the POSIX popen/pclose directly.
C#: ProcessStartInfo.RedirectStandardOutput + Process.StandardOutput; UseShellExecute=false both skips the shell and enables redirection.
Go: exec.Command(...).Output() reads stdout in one shot (err is *ExitError carrying the status); StdoutPipe() is the streaming variant.
Java: ProcessBuilder + getInputStream() + waitFor(); Runtime.exec is the legacy API.
JS/TS: child_process.execSync/exec (via /bin/sh) return the stdout Buffer; mind the exec family's maxBuffer cap.
Python: subprocess.Popen(..., stdout=PIPE) is the exact counterpart; communicate() reads to EOF and reaps; modern code prefers subprocess.run(capture_output=True).
Rust: Command::output() reads in one shot (status carries the code); stdout(Stdio::piped()) + spawn is the streaming variant.
Portability: the example's echo works on macOS and Linux alike; on Windows substitute a cmd builtin or the corresponding executable (e.g. cmd /c echo ...).