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

The proc_open trio: proc_get_status polls the child's state (running/exitcode/stopped), proc_close blocks to reap and yields the exit code, proc_terminate sends a kill signal - stopping and reaping are two steps, kill first then reap.

C C23

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 is the POSIX counterpart of proc_open */
    pid_t pid = fork();
    if (pid == 0) {
        int dn = open("/dev/null", O_WRONLY);
        dup2(dn, 1); /* we only care about the exit status, not the output */
        execlp("echo", "echo", "done", (char *)NULL);
        _exit(127);
    }

    /* a WNOHANG waitpid polls like proc_get_status, without blocking */
    int status = 0;
    pid_t r = waitpid(pid, &status, WNOHANG);
    printf("still running: %s\n", r == 0 ? "true" : "false");
    waitpid(pid, &status, 0); /* reap: the proc_close counterpart */
    printf("exit code: %d\n", WEXITSTATUS(status));

    /* terminate and reap are two separate steps: SIGTERM first, wait second */
    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;
}
Output
still running: true
exit code: 0
sleep running: true
signaled: true (sig 15)

C++ C++26

C++26
#include <fcntl.h>
#include <csignal>
#include <cstdlib>
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>

int main() {
    // fork+execlp is the POSIX counterpart of proc_open
    pid_t pid = fork();
    if (pid == 0) {
        int dn = open("/dev/null", O_WRONLY);
        dup2(dn, 1); // we only care about the exit status, not the output
        execlp("echo", "echo", "done", (char *)nullptr);
        _exit(127);
    }

    // a WNOHANG waitpid polls like proc_get_status, without blocking
    int status = 0;
    pid_t r = waitpid(pid, &status, WNOHANG);
    std::cout << "still running: " << (r == 0 ? "true" : "false") << "\n";
    waitpid(pid, &status, 0); // reap: the proc_close counterpart
    std::cout << "exit code: " << WEXITSTATUS(status) << "\n";

    // terminate and reap are two separate steps: SIGTERM first, wait second
    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;
}
Output
still running: true
exit code: 0
sleep running: true
signaled: true (sig 15)

C# v11.0.100

v11.0.100
using System.Diagnostics;

// Start + WaitForExit: spawn, then reap and read the exit code
var echoPsi = new ProcessStartInfo("echo", "done") { RedirectStandardOutput = true };
using var echo = Process.Start(echoPsi)!;
_ = echo.StandardOutput.ReadToEnd(); // drain the pipe before reaping
Console.WriteLine("exit code: " + echo.ExitCode); // set after WaitForExit in .NET 5+

// Kill first, WaitForExit second: terminate and reap are two steps
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);
Output
exit code: 0
sleep pid set: True
killed exit code: 137

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os/exec"
)

func main() {
	// Run = Start + Wait: spawn, reap, collect the exit code
	cmd := exec.Command("echo", "done")
	if err := cmd.Run(); err != nil {
		panic(err)
	}
	fmt.Println("exit code:", cmd.ProcessState.ExitCode())

	// Kill first, Wait second: terminate and reap are two separate steps
	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)
}
Output
exit code: 0
sleep started: true
wait after kill: signal: killed

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) throws Exception {
        // waitFor both reaps the child and yields its exit code
        Process echo = new ProcessBuilder("echo", "done").start();
        System.out.println("exit code: " + echo.waitFor());

        // destroyForcibly first, waitFor second: stop and reap are two steps
        Process sleep = new ProcessBuilder("sleep", "30").start();
        System.out.println("sleep alive: " + sleep.isAlive());
        sleep.destroyForcibly();
        System.out.println("destroyed exit code: " + sleep.waitFor());
    }
}
Output
exit code: 0
sleep alive: true
destroyed exit code: 137

JavaScript v26.13.1

v26.13.1
// the close event fires only after the child is reaped, and carries the code
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 first, close event second: terminate and reap are two steps
    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");
    });
});
Output
done
exit code: 0
running: true
terminated: true

PHP v8.6.0

v8.6.0
// 1) status -> close: a short-lived child exits on its own
$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: stop it first, then reap - two distinct steps
$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); // default SIGTERM
usleep(200000); // let the signal land before polling again
echo 'after terminate: ', var_export(proc_get_status($proc2)['running'], true), "\n";
echo 'close after terminate: ', proc_close($proc2), "\n";
Output
running: true exitcode: -1
done
close exit: 0
sleep running: true
after terminate: false
close after terminate: -1

Python v3.15.2

v3.15.2
import subprocess

# poll() -> None means still running; wait() reaps and returns the code
proc = subprocess.Popen(["echo", "done"], stdout=subprocess.PIPE, text=True)
print("output:", proc.stdout.read().strip())
print("exit code:", proc.wait())

# terminate() first, wait() second: stop and reap are two separate steps
sleeper = subprocess.Popen(["sleep", "30"])
print("running:", sleeper.poll() is None)
sleeper.terminate()
print("code after terminate:", sleeper.wait())  # -15 = killed by SIGTERM
Output
output: done
exit code: 0
running: True
code after terminate: -15

Rust v1.99.1

v1.99.1
use std::os::unix::process::ExitStatusExt;
use std::process::{Command, Stdio};

fn main() {
    // status(): spawn, wait, collect the exit code in one call
    // (stdout to /dev/null: we only care about the status here)
    let st = Command::new("echo")
        .arg("done")
        .stdout(Stdio::null())
        .status()
        .unwrap();
    println!("exit code: {}", st.code().unwrap());

    // kill first, wait second: terminate and reap are two separate steps
    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());
}
Output
exit code: 0
killed by signal: 9

TypeScript v26.13.1

v26.13.1
// the close event fires only after the child is reaped, and carries the code
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 first, close event second: terminate and reap are two steps
    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");
    });
});
Output
done
exit code: 0
running: true
terminated: true

Language differences

c: the POSIX prototype of the "proc_open trio": fork+execlp spawns, a WNOHANG waitpid stands in for proc_get_status (polling, non-blocking), waitpid(...,0) for proc_close (blocking reap), kill(2) for proc_terminate; the example includes <sys/wait.h> and <signal.h> explicitly - WIFSIGNALED/WTERMSIG and kill are declared there. A signal-killed child has no exit code, only a terminating signal (sig 15 = SIGTERM).

cpp: fully isomorphic to C (the example is the same flow in C++); the C++ standard library has no process API - spawn either via this POSIX route or via boost::process.

csharp: Process.Start spawns, WaitForExit reaps, Kill terminates - Kill must be followed by WaitForExit, or zombie handles linger; .NET's Kill is SIGKILL-equivalent, hence exit code 137 = 128+9 in the example. The ExitCode property is unreliable until reaping completes.

go: cmd.Run() merges Start+Wait into one step; to split them, go Start -> Process.Kill -> Wait manually. The error Wait returns is an *ExitError, printed as "signal: killed" here - even after Kill, Wait blocks until the child is really gone: stopping and reaping are always two steps.

java: waitFor() combines "reap + give exit code"; destroy() sends SIGTERM, destroyForcibly() SIGKILL (the example uses the latter, exit code constantly 137 = 128+9 on POSIX). isAlive() is the polling counterpart.

javascript: no synchronous process API: spawn starts, the close event both reports the exit code and marks the reap; kill() defaults to SIGTERM, and for a killed child the close callback gets code null and the signal name. Mind the difference between close (stdio fully closed) and exit (process just exited).

php: proc_get_status polls running/exitcode/stopped (exitcode is constantly -1 while running, filled in after exit); proc_close reaps with a blocking wait and yields the exit code, and it expects all pipes fclose'd first for a clean result; proc_terminate defaults to SIGTERM (a second argument swaps the signal), and the child does not vanish the instant the signal is sent - the example sleeps, then polls running to see it turn false; a signal-killed child makes proc_close return -1. Windows has no SIGTERM semantics, and POSIX commands like sleep/echo are unavailable (the example targets POSIX; on Windows use cmd builtins and adjust the assertions).

python: Popen.poll() polls without blocking (None = still running), wait() reaps, terminate() = SIGTERM, kill() = SIGKILL; a signal-killed returncode is negative (-15) - "minus the signal number" is Python's encoding convention. Switch to communicate() when output is large to avoid pipe deadlock.

rust: Child::kill sends SIGKILL - note the difference from PHP/Java's default SIGTERM: SIGKILL cannot be caught or ignored, it is the "certain kill"; wait() reaps into an ExitStatus, and .signal() reads the terminating signal on Unix (needs use std::os::unix::process::ExitStatusExt, a platform-specific trait absent on Windows). The example prints 9 = SIGKILL.

typescript: same as JavaScript (spawn + close event model).

common ground: stopping (terminate/destroy/kill) and reaping (close/wait/reap) are two steps in every language - kill without reap and the child becomes a zombie holding its PID; that is the iron rule of the POSIX process model.