proc_get_status / proc_close / proc_terminate
proc_get_status(resource $process): array; proc_close(resource $process): int; proc_terminate(resource $process, int $signal = 15): bool
proc_open 三件套:proc_get_status 轮询子进程状态(running/exitcode/stopped),proc_close 阻塞回收并给退出码,proc_terminate 发信号强杀——终止与回收是两步,先杀后收。
C C23
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
/* fork+execlp 是 proc_open 的 POSIX 对应物 */
pid_t pid = fork();
if (pid == 0) {
int dn = open("/dev/null", O_WRONLY);
dup2(dn, 1); /* 只关心退出状态,不关心输出 */
execlp("echo", "echo", "done", (char *)NULL);
_exit(127);
}
/* WNOHANG 的 waitpid 如同 proc_get_status 轮询,且不阻塞 */
int status = 0;
pid_t r = waitpid(pid, &status, WNOHANG);
printf("still running: %s\n", r == 0 ? "true" : "false");
waitpid(pid, &status, 0); /* 回收:对应 proc_close */
printf("exit code: %d\n", WEXITSTATUS(status));
/* 终止与回收是两步:先 SIGTERM,后 wait */
pid_t pid2 = fork();
if (pid2 == 0) { execlp("sleep", "sleep", "30", (char *)NULL); _exit(127); }
r = waitpid(pid2, &status, WNOHANG);
printf("sleep running: %s\n", r == 0 ? "true" : "false");
kill(pid2, SIGTERM);
waitpid(pid2, &status, 0);
printf("signaled: %s (sig %d)\n", WIFSIGNALED(status) ? "true" : "false", WTERMSIG(status));
return 0;
}
still running: true exit code: 0 sleep running: true signaled: true (sig 15)
C++ C++26
#include <fcntl.h>
#include <csignal>
#include <cstdlib>
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
int main() {
// fork+execlp 是 proc_open 的 POSIX 对应物
pid_t pid = fork();
if (pid == 0) {
int dn = open("/dev/null", O_WRONLY);
dup2(dn, 1); // 只关心退出状态,不关心输出
execlp("echo", "echo", "done", (char *)nullptr);
_exit(127);
}
// WNOHANG 的 waitpid 如同 proc_get_status 轮询,且不阻塞
int status = 0;
pid_t r = waitpid(pid, &status, WNOHANG);
std::cout << "still running: " << (r == 0 ? "true" : "false") << "\n";
waitpid(pid, &status, 0); // 回收:对应 proc_close
std::cout << "exit code: " << WEXITSTATUS(status) << "\n";
// 终止与回收是两步:先 SIGTERM,后 wait
pid_t pid2 = fork();
if (pid2 == 0) { execlp("sleep", "sleep", "30", (char *)nullptr); _exit(127); }
r = waitpid(pid2, &status, WNOHANG);
std::cout << "sleep running: " << (r == 0 ? "true" : "false") << "\n";
kill(pid2, SIGTERM);
waitpid(pid2, &status, 0);
std::cout << "signaled: " << (WIFSIGNALED(status) ? "true" : "false")
<< " (sig " << WTERMSIG(status) << ")\n";
return 0;
}
still running: true exit code: 0 sleep running: true signaled: true (sig 15)
C# v11.0.100
using System.Diagnostics;
// Start + WaitForExit:先起子进程,再回收并读退出码
var echoPsi = new ProcessStartInfo("echo", "done") { RedirectStandardOutput = true };
using var echo = Process.Start(echoPsi)!;
_ = echo.StandardOutput.ReadToEnd(); // 回收前排干管道
Console.WriteLine("exit code: " + echo.ExitCode); // .NET 5+ 在 WaitForExit 后自动可用
// 先 Kill,后 WaitForExit:终止与回收是两步
using var sleep = Process.Start(new ProcessStartInfo("sleep", "30"))!;
Console.WriteLine("sleep pid set: " + (sleep.Id > 0));
sleep.Kill();
sleep.WaitForExit();
Console.WriteLine("killed exit code: " + sleep.ExitCode);
exit code: 0 sleep pid set: True killed exit code: 137
Go v1.27.4
package main
import (
"fmt"
"os/exec"
)
func main() {
// Run = Start + Wait 一步合并:起进程、回收、取退出码
cmd := exec.Command("echo", "done")
if err := cmd.Run(); err != nil {
panic(err)
}
fmt.Println("exit code:", cmd.ProcessState.ExitCode())
// 先 Kill,后 Wait:终止与回收是两个独立的步骤
sleeper := exec.Command("sleep", "30")
if err := sleeper.Start(); err != nil {
panic(err)
}
fmt.Println("sleep started:", sleeper.Process != nil)
if err := sleeper.Process.Kill(); err != nil {
panic(err)
}
err := sleeper.Wait()
fmt.Println("wait after kill:", err)
}
exit code: 0 sleep started: true wait after kill: signal: killed
Java v27.0.1
public class Main {
public static void main(String[] args) throws Exception {
// waitFor 一肩挑「回收 + 给退出码」
Process echo = new ProcessBuilder("echo", "done").start();
System.out.println("exit code: " + echo.waitFor());
// 先 destroyForcibly,后 waitFor:终止与回收是两步
Process sleep = new ProcessBuilder("sleep", "30").start();
System.out.println("sleep alive: " + sleep.isAlive());
sleep.destroyForcibly();
System.out.println("destroyed exit code: " + sleep.waitFor());
}
}
exit code: 0 sleep alive: true destroyed exit code: 137
JavaScript v26.13.1
// close 事件只在子进程被回收后触发,并携带退出码
const { spawn } = require("child_process");
const echo = spawn("echo", ["done"]);
echo.stdout.on("data", (chunk) => process.stdout.write(chunk));
echo.on("close", (code) => {
console.log("exit code:", code);
// 先 kill,close 事件后到:终止与回收是两步
const sleeper = spawn("sleep", ["30"]);
console.log("running:", sleeper.exitCode === null);
sleeper.kill("SIGTERM");
sleeper.on("close", (code2, signal) => {
console.log("terminated:", code2 === null && signal === "SIGTERM");
});
});
done exit code: 0 running: true terminated: true
PHP v8.6.0
// 1) status -> close:短命子进程自行退出
$proc = proc_open(['echo', 'done'], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
fclose($pipes[0]);
$st = proc_get_status($proc);
echo 'running: ', var_export($st['running'], true), ' exitcode: ', $st['exitcode'], "\n";
echo stream_get_contents($pipes[1]);
fclose($pipes[1]); fclose($pipes[2]);
echo 'close exit: ', proc_close($proc), "\n";
// 2) terminate -> close:先终止,后回收——两个独立的步骤
$proc2 = proc_open(['sleep', '30'], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes2);
fclose($pipes2[0]); fclose($pipes2[1]); fclose($pipes2[2]);
echo 'sleep running: ', var_export(proc_get_status($proc2)['running'], true), "\n";
proc_terminate($proc2); // 默认 SIGTERM
usleep(200000); // 给信号一点时间落地,再轮询
echo 'after terminate: ', var_export(proc_get_status($proc2)['running'], true), "\n";
echo 'close after terminate: ', proc_close($proc2), "\n";
running: true exitcode: -1 done close exit: 0 sleep running: true after terminate: false close after terminate: -1
Python v3.15.2
import subprocess
# poll() -> None 表示还在跑;wait() 负责回收并返回退出码
proc = subprocess.Popen(["echo", "done"], stdout=subprocess.PIPE, text=True)
print("output:", proc.stdout.read().strip())
print("exit code:", proc.wait())
# 先 terminate(),后 wait():终止与回收是两个独立的步骤
sleeper = subprocess.Popen(["sleep", "30"])
print("running:", sleeper.poll() is None)
sleeper.terminate()
print("code after terminate:", sleeper.wait()) # -15 = 被 SIGTERM 杀死
output: done exit code: 0 running: True code after terminate: -15
Rust v1.99.1
use std::os::unix::process::ExitStatusExt;
use std::process::{Command, Stdio};
fn main() {
// status():起进程、等待、取退出码一步完成
//(stdout 重定向到 /dev/null:这里只关心状态)
let st = Command::new("echo")
.arg("done")
.stdout(Stdio::null())
.status()
.unwrap();
println!("exit code: {}", st.code().unwrap());
// 先 kill,后 wait:终止与回收是两个独立的步骤
let mut child = Command::new("sleep").arg("30").spawn().unwrap();
child.kill().unwrap();
let st = child.wait().unwrap();
println!("killed by signal: {}", st.signal().unwrap());
}
exit code: 0 killed by signal: 9
TypeScript v26.13.1
// close 事件只在子进程被回收后触发,并携带退出码
import { spawn } from "child_process";
const echo = spawn("echo", ["done"]);
echo.stdout.on("data", (chunk: Buffer) => process.stdout.write(chunk));
echo.on("close", (code: number | null) => {
console.log("exit code:", code);
// 先 kill,close 事件后到:终止与回收是两步
const sleeper = spawn("sleep", ["30"]);
console.log("running:", sleeper.exitCode === null);
sleeper.kill("SIGTERM");
sleeper.on("close", (code2: number | null, signal: NodeJS.Signals | null) => {
console.log("terminated:", code2 === null && signal === "SIGTERM");
});
});
done exit code: 0 running: true terminated: true
语言差异说明
c:「proc_open 三件套」的 POSIX 原形:fork+execlp 起子进程,WNOHANG 的 waitpid 充当 proc_get_status(轮询、不阻塞),waitpid(...,0) 充当 proc_close(阻塞回收),kill(2) 充当 proc_terminate;示例显式包含 <sys/wait.h> 与 <signal.h>——WIFSIGNALED/WTERMSIG 与 kill 的声明分属两者。被信号终止的子进程没有退出码,只有终止信号(sig 15 = SIGTERM)。
cpp:与 C 完全同构(示例即 C 流程的 C++ 写法);C++ 标准库没有进程 API,起子进程要么走 POSIX 这一套,要么引入 boost::process。
csharp:Process.Start 起、WaitForExit 收、Kill 杀——Kill 后必须再 WaitForExit,只杀不收会留僵尸句柄;.NET 的 Kill 等价于 SIGKILL,示例退出码 137 = 128+9。ExitCode 属性在回收完成前不可靠。
go:cmd.Run() 把 Start+Wait 合并成一步;要分步就得手动 Start → Process.Kill → Wait。Wait 返回的 error 是 *ExitError,示例直接打印其 "signal: killed" 消息——即使已 Kill,Wait 仍会阻塞到子进程真正消失,终止与回收始终两步。
java:waitFor() 一肩挑「回收+给退出码」;destroy() 发 SIGTERM、destroyForcibly() 发 SIGKILL(示例用后者,POSIX 上退出码恒 137 = 128+9)。isAlive() 是轮询语义的对应物。
javascript:没有同步进程 API:spawn 起、close 事件既报退出码也标志回收完成;kill() 默认 SIGTERM,被杀进程的 close 回调里 code 为 null、signal 为信号名。注意区分 close(stdio 已关闭)与 exit(进程刚退出)。
php:proc_get_status 轮询 running/exitcode/stopped(运行中 exitcode 恒 -1,退出后才回填);proc_close 阻塞回收并给退出码,且它要求 pipes 全部 fclose 之后才返回干净结果;proc_terminate 默认发 SIGTERM(第二参可换信号),发完信号子进程不是瞬间消失——示例 usleep 后再轮询 running 才变 false;被信号杀死的进程 proc_close 返回 -1。Windows 下无 SIGTERM 语义,且 sleep/echo 等 POSIX 命令不可用(示例为 POSIX 环境;Windows 需换 cmd 内建命令并调整断言)。
python:Popen.poll() 非阻塞轮询(None = 还在跑),wait() 回收,terminate() = SIGTERM、kill() = SIGKILL;信号终止的 returncode 是负数(-15),「负号+信号号」是 Python 的编码约定。输出量大时换 communicate() 防管道死锁。
rust:Child::kill 发 SIGKILL——注意与 PHP/Java 默认的 SIGTERM 不同:SIGKILL 不可被捕获或忽略,语义上是「必杀」;wait() 回收并给 ExitStatus,Unix 上用 .signal() 取终止信号(需 use std::os::unix::process::ExitStatusExt,平台特定 trait,Windows 分支无此方法)。示例输出 9 = SIGKILL。
typescript:同 JavaScript(spawn + close 事件模型)。
共性:终止(terminate/destroy/kill)与回收(close/wait/reap)在所有语言里都是两步——杀完不收,子进程变僵尸(zombie)持续占用 PID,这是 POSIX 进程模型的铁律。