proc_open
proc_open(array|string $command, array $descriptor_spec, array &$pipes, ?string $cwd = null, ?array $env_vars = null, ?array $options = null): resource|false
开启双向管道的子进程:descriptor_spec 定义 0/1/2 的走向,$pipes 收 PHP 端句柄,proc_close 回收;exec 家族里唯一能双向通信的。
C C23
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
/* popen(3) 只有一个方向;真正的双向管道要手写
pipe(2) + fork(2) + execlp(3) */
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) {
/* 子进程:stdin <- in_pipe 读端,stdout -> out_pipe 写端 */
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;
}
pipe talk exit code: 0
C++ C++26
#include <cstdio>
#include <iostream>
int main() {
// popen(3) 设计上就是单向的:"r" 只读 stdout,没法喂 stdin——
// 相对 PHP 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;
}
pipe talk exit code: 0
C# v11.0.100
// ProcessStartInfo 配 RedirectStandardInput/Output:双向通信
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);
pipe talk exit code: 0
Go v1.27.4
package main
import (
"fmt"
"os/exec"
)
func main() {
// exec.Command + StdinPipe/StdoutPipe:通向子进程的双向管道
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())
}
pipe talk exit code: 0
Java 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 喂子进程 stdin,getInputStream
// 读它的 stdout——双向,与 proc_open 同构
Process proc = new ProcessBuilder("cat").start();
OutputStream in = proc.getOutputStream();
in.write("pipe talk\n".getBytes());
in.close(); // 给 cat 发 EOF
InputStream out = proc.getInputStream();
byte[] buf = out.readAllBytes();
System.out.print(new String(buf));
System.out.println("exit code: " + proc.waitFor());
}
}
pipe talk exit code: 0
JavaScript v26.13.1
// child_process.spawn:stdio 管道同样能双向通信
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));
pipe talk exit code: 0
PHP v8.6.0
// proc_open:数组命令(PHP 7.4+)不经 shell 直接执行;管道双向通信
// (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]); // 关掉自己的写端,cat 才能见到 EOF
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
echo 'exit code: ', proc_close($proc), "\n";
bool(true) pipe talk exit code: 0
Python v3.15.2
import subprocess
# subprocess.Popen 配 stdin/stdout 管道:与子进程双向通信
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())
pipe talk exit code: 0
Rust v1.99.1
use std::io::Read;
use std::io::Write;
use std::process::{Command, Stdio};
fn main() {
// Command 配管道 stdin/stdout:take() 把管道句柄拿走
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); // 关掉自己的端,cat 才能见到 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());
}
pipe talk exit code: 0
TypeScript v26.13.1
// child_process.spawn:stdio 管道同样能双向通信
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));
pipe talk exit code: 0
语言差异说明
C:popen(3) 只有一个方向("r" 或 "w" 二选一)——双向要手写 pipe(2)+fork(2)+dup2+execlp(3) 本例全套;waitpid+WEXITSTATUS 回收。
C++:同 C 的 popen 局限(本例演示单向 "r");要双向走 pipe/fork 手写或 boost::process。
C#:ProcessStartInfo 的 RedirectStandardInput/Output 布尔开关 + StandardInput.WriteAsync/StandardOutput.ReadToEnd()——注意 Output 异步事件(OutputDataReceived)与同步 ReadToEnd 不能混用(会死锁)。
Go:exec.Command + StdinPipe()/StdoutPipe() 显式管道句柄;或直接 cmd.Stdin = strings.NewReader(...)(io.Writer/Reader 注入更 Go 风)。
Java:ProcessBuilder + getOutputStream()(喂子进程 stdin)/getInputStream()(读子进程 stdout)——API 方向以「父进程视角」命名,第一次用极易搞反。
JavaScript:child_process.spawn 的 stdin/stdout 是完整流(可 pipe 链接);exec 则是缓冲回调式(execBufSize 上限);本例 spawn 与 PHP proc_open 同构。
PHP:proc_open 是 exec/system/shell_exec/popen 家族里唯一双向的——descriptor_spec 数组定义 0/1/2(还能开 >2 的自定义描述符给协同进程传密钥,手册明示);command 传数组(PHP 7.4+)不经 shell、由 PHP 负责转义(手册明示,跨平台更安全);返回 resource 用 proc_close 回收(PHP 8.3 起空 command 数组抛 ValueError);proc_get_status 可查运行状态;proc_terminate 强杀。Windows 注意:cat 等 Unix 命令不可用(本条目演示命令是 cat,macOS/Linux 通用,Windows 需换 findstr/PowerShell 或注释掉)。
Python:subprocess.Popen(stdin=PIPE, stdout=PIPE) 双向;subprocess.run(input=...) 是一次性 convenienc; communicate() 防「管道缓冲写满互相等死」的经典死锁(本例文本小不触发)。
Rust:Command::stdin(Stdio::piped()) + child.stdin.take().unwrap()(take 拿走 Option 句柄);drop(stdin) 显式关端发 EOF——所有权模型让「谁持有管道」一目了然。
TypeScript:同 JavaScript(spawn 流管道)。