fastexec

package module
v0.0.0-...-4500a58 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 28, 2026 License: Apache-2.0 Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

fastexec

Go Reference

Package fastexec is a high-throughput, low-latency alternative to os/exec for spawning external processes on Linux and Darwin (macOS).

Why

os/exec favors portability and conservative safety. Under high spawn rates that conservatism becomes the bottleneck:

  • Every spawn serializes on the global syscall.ForkLock (an exclusive sync.RWMutex), so spawn throughput degrades as parallelism increases.
  • Argument and environment marshaling allocates a fresh NUL-terminated copy of every string on every spawn, pressuring the GC.
  • exec.CommandContext cancellation signals the child by PID, which is subject to PID-reuse races on busy systems.
  • On Darwin, fork(2) from a large multithreaded process risks pthread_atfork deadlocks and copy-on-write stalls; Apple explicitly discourages fork+exec in favor of posix_spawn(2).

fastexec removes each of these costs with platform-specific process-creation primitives while keeping an os/exec-shaped API.

Design

Linux (amd64, arm64)
  • Processes are created with a raw clone3(2) system call using CLONE_VFORK | CLONE_VM: the parent's page tables are never copied, so spawn latency is O(1) in the parent's heap size.
  • CLONE_PIDFD returns a pidfd atomically at creation. Waiting uses waitid(P_PIDFD) and signaling uses pidfd_send_signal(2), so cancellation can never hit a recycled PID.
  • CLONE_CLEAR_SIGHAND (Linux 5.5+) resets every signal disposition inside the child atomically, so no Go signal handler can ever run in the shared address space: the fast path performs no signal masking and no thread pinning at all. Kernels that reject the flag (5.4) latch a transparent fallback that blocks all signals across the vfork window and has the child restore the mask before exec — the pre-optimization behavior.
  • The vfork child runs entirely in hand-written assembly (amd64 and arm64) on a private stack until execve(2) — no Go runtime code, no stack growth.
  • Stdio sources already at fd >= 3 (the /dev/null singleton, os.Pipe ends, regular files) are handed to the child without any dup-up; the child's dup3 onto 0–2 cannot collide because every source sits above the target range. Only sources at fds 0–2 are lifted with F_DUPFD_CLOEXEC. Non-CLOEXEC sources appear in the child at their original descriptor, exactly like os/exec.
  • syscall.ForkLock is not taken, so spawns scale with CPU count. A steady-state spawn costs the parent three system calls: clone3, waitid, close (see the syscall table below).
  • Environments whose seccomp policy rejects clone3 (Docker's default profile returns ENOSYS) transparently fall back to clone(2) with the same flags. Kernels that do not honor CLONE_VM sharing for vfork children (observed on OrbStack) are detected with a one-time probe, and exec-failure reporting switches to a CLOEXEC pipe, exactly like os/exec.
  • Requires Linux 5.4+ (clone3/clone(CLONE_PIDFD) plus waitid(P_PIDFD)); 5.5+ engages the no-masking fast path.
Darwin (amd64, arm64)
  • Processes are created with posix_spawn(2) — the only fork-safe primitive Apple supports for multithreaded programs. The kernel handles the intermediate child state, avoiding pthread_atfork deadlocks and copy-on-write stalls entirely.
  • posix_spawn is reached through a direct libSystem call using the same trampoline mechanism as golang.org/x/sys/unix (dynamic import + Go runtime libc gate), not cgo — there is no cgo call overhead.
  • The spawn attribute (POSIX_SPAWN_SETSIGDEF | SETSIGMASK | CLOEXEC_DEFAULT — identical for every spawn) is initialized once per pooled spawn state and destroyed by a runtime.AddCleanup, dropping five libc calls from every spawn. The remaining per-spawn bookkeeping (file-actions init/dup2/chdir/destroy) goes through syscall.rawSyscall6 — no scheduler round trip; only the blocking posix_spawn itself pays entersyscall. The Cmd path makes 6 libc calls per spawn.
  • A Spec (see below) with all-nil stdio freezes its file actions at construction: such a spawn is one posix_spawn libc call plus the wait4 — the platform floor without reimplementing Apple's private __posix_spawn ABI.
  • POSIX_SPAWN_CLOEXEC_DEFAULT guarantees that no descriptor other than the three mapped stdio descriptors reaches the child — even descriptors opened without O_CLOEXEC — with no ForkLock.
Both platforms
  • argv/envp/path strings are marshaled into a pooled, reusable arena as NUL-terminated C strings referenced by raw pointers: steady-state spawning performs no per-string heap allocations.
  • Cmd.Process and Cmd.ProcessState are value fields, (*Cmd).Reset returns a Cmd to its pre-start state, and the nil-Env environment snapshot is cached process-wide (InvalidateEnv refreshes it): a reused Cmd with preset Env and every Spec.Run spawn zero heap allocations (testing.AllocsPerRun == 0, enforced in tests).
  • Spec freezes PATH resolution, argv, env, and dir at construction into a retained arena; it is immutable and safe for concurrent use — built for hot loops and worker pools running one command many times.
  • Stdio is *os.File only (nil means a shared /dev/null), so the hot path starts no goroutines and copies no data. Output and CombinedOutput build the pipes for you when convenience matters.

Usage

import "github.com/zchee/fastexec"

// Drop-in shape for the common cases.
out, err := fastexec.Command("git", "rev-parse", "HEAD").Output()

// Context cancellation kills through a pidfd on Linux: no PID-reuse race.
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
err = fastexec.CommandContext(ctx, "sleep", "30").Run()

// Zero-allocation respawn loop: preset Env, reuse the Cmd via Reset.
c := fastexec.Command("/usr/bin/worker")
c.Env = os.Environ()
for range jobs {
	if err := c.Run(); err != nil { ... }
	c.Reset()
}

// Spec: freeze the command once, spawn concurrently with 0 allocs/op.
spec, err := fastexec.NewSpec("/usr/bin/worker", []string{"--fast"}, nil, "")
if err != nil { ... }
var ps fastexec.ProcessState
if err := spec.Run(nil, nil, nil, &ps); err != nil { ... }

// After os.Setenv, refresh the cached nil-Env snapshot.
os.Setenv("MODE", "prod")
fastexec.InvalidateEnv()

Benchmarks

Spawning /usr/bin/true, Go 1.26. benchstat over 10 runs; os/exec numbers from the same sessions serve as drift control.

Apple M3 Max (Darwin arm64, 16 cores):

BenchmarkRunFastexec-16          1.402m ± 2%    419 B/op    2 allocs/op
BenchmarkRunFastexecReset-16     1.414m ± 2%      0 B/op    0 allocs/op
BenchmarkRunSpec-16              1.397m ± 3%      0 B/op    0 allocs/op
BenchmarkRunOsExec-16            2.469m ± 1%   1336 B/op   25 allocs/op
BenchmarkRunParallelSpec-16       149.0µ ±14%      0 B/op    0 allocs/op
BenchmarkRunParallelFastexec-16   157.3µ ±26%    419 B/op    2 allocs/op
BenchmarkRunParallelOsExec-16     485.0µ ± 1%   1399 B/op   25 allocs/op

Linux arm64 (lima VM, Ubuntu 6.17 kernel, 8 vCPU):

BenchmarkRunFastexec-8            220.2µ ± 2%    412 B/op    2 allocs/op
BenchmarkRunFastexecReset-8       219.2µ ± 2%      0 B/op    0 allocs/op
BenchmarkRunSpec-8                220.2µ ± 3%      0 B/op    0 allocs/op
BenchmarkRunOsExec-8              243.4µ ± 1%   1576 B/op   30 allocs/op
BenchmarkRunParallelSpec-8        34.19µ ± 1%      0 B/op    0 allocs/op
BenchmarkRunParallelFastexec-8    34.73µ ± 7%    415 B/op    2 allocs/op
BenchmarkRunParallelOsExec-8      44.84µ ± 5%   1576 B/op   30 allocs/op

1.8x (sequential) to 3.3x (parallel) faster on Darwin, 1.1–1.3x on Linux, with zero steady-state allocations against 25–30 for os/exec.

Parallel scaling (-cpu sweep, Spec.Run vs os/exec)

The gap widens with core count because os/exec serializes on ForkLock while fastexec never takes it — on Darwin os/exec stops scaling entirely past 8 cores:

GOMAXPROCS darwin Spec darwin os/exec ratio linux Spec linux os/exec ratio
1 1447µs 2441µs 1.7x 225µs 246µs 1.1x
4 326µs 648µs 2.0x 61.6µs 68.2µs 1.1x
8 177µs 482µs 2.7x 34.1µs 44.7µs 1.3x
16 149µs 485µs 3.3x — — —
Large-heap parent (4 GiB touched ballast)

Darwin os/exec forks, so spawn cost grows with the parent's memory image; posix_spawn does not: with a 4 GiB ballast os/exec degrades 2.44ms → 2.75ms (+12%) while Spec.Run stays within noise of its no-ballast time (~1.46ms median). On Linux both are vfork-class and neither degrades. (Run with FASTEXEC_BENCH_BALLAST_GIB=4.)

Syscall profile

strace -f -c over 1000 warmed Spec.Run spawns (lima, Ubuntu 6.17.0-29 arm64) — the parent-side cost per spawn is exactly 3 syscalls (clone3 + waitid + close); fcntl, pipe2, and rt_sigprocmask appear only as O(1) startup/probe totals:

     calls    errors syscall          per spawn
      1024        22 waitid           1 (parent)
      1002           clone3           1 (parent)
      3007           close            1 (parent) + 2 (child loader)
      3006           dup3             3 (child stdio wiring)
      1003         1 execve           1 (child)
        14           rt_sigprocmask   0 (runtime startup only)
        10           fcntl            0 (probe only)
         0           pipe2            0 (shared-memory errno mode)

An exit_signal=0 experiment (suppressing the SIGCHLD delivered into the Go runtime per child exit) produced no statistically significant parallel win on a 6.17 kernel (p ≥ 0.14 across two A/B methodologies) and was dropped per the optimization plan's measurement gate.

Differences from os/exec

  • Stdin/Stdout/Stderr are *os.File, not io.Reader/io.Writer; nil means /dev/null. Use os.Pipe for streaming.
  • Cmd.Process and Cmd.ProcessState are value fields; a Cmd must not be copied after first use. ExitError embeds its own ProcessState copy and survives Reset.
  • A Cmd is respawnable via (*Cmd).Reset() instead of being single-use.
  • With nil Env the environment snapshot is cached process-wide; call InvalidateEnv() after os.Setenv and friends. Entries are passed to the kernel verbatim (no deduplication).
  • Children always start with default signal dispositions and an empty signal mask.
  • Process signaling is Process.Signal(unix.Signal) / Process.Kill(), through a pidfd on Linux.
  • Unsupported os/exec features: ExtraFiles, SysProcAttr, Cancel, WaitDelay, and StdinPipe-style helpers.

Cmd methods must not be called concurrently; Spec is safe for concurrent use.

Environment knobs (testing/triage)
  • FASTEXEC_NO_CLEAR_SIGHAND=1 forces the Linux signal-mask fallback even on kernels that support CLONE_CLEAR_SIGHAND.

Requirements

  • Go 1.26+
  • Linux 5.4+ on amd64 or arm64 (5.5+ engages the no-masking fast path), or any supported Darwin (macOS 10.15+ if Cmd.Dir/NewSpec dir is used, for posix_spawn_file_actions_addchdir_np)

Acknowledgments

The design distills the optimization strategies surveyed in a deep-research report on pushing exec.Command beyond its limits: vfork-class cloning to avoid page-table duplication, ForkLock-free descriptor management on atomic O_CLOEXEC kernels, arena-based zero-allocation argv/envp marshaling, pidfd-based lifecycle management, and posix_spawn on Darwin.

License

Apache License 2.0. See LICENSE.

Documentation

Overview

Package fastexec is a high-throughput, low-latency alternative to os/exec for spawning external processes on Linux and Darwin (macOS).

The standard os/exec package favors portability and conservative safety: every spawn serializes on the global syscall.ForkLock, converts argv and environment strings with per-string heap allocations, and (on cancel) signals the child by PID, which is subject to PID-reuse races. fastexec removes those costs with platform-specific process-creation primitives:

  • Linux: processes are created with a raw clone3(2) system call using CLONE_VFORK|CLONE_VM, so the parent's page tables are never copied regardless of the parent's heap size, and CLONE_PIDFD, so cancellation and signaling use pidfd_send_signal(2) and can never hit a recycled PID. CLONE_CLEAR_SIGHAND (Linux 5.5+) resets every signal disposition inside the child atomically, so no Go signal handler can run in the shared address space and the fast path needs no signal masking or thread pinning at all (older kernels and the clone(2) seccomp fallback transparently latch a mask-and-restore fallback). The child runs entirely in hand-written assembly on a private stack until execve(2), and syscall.ForkLock is not taken: stdio sources already above the exec target range are handed to the child as-is, so a steady-state spawn costs the parent three system calls (clone3, waitid, close). Requires Linux 5.4+ (clone3 and waitid P_PIDFD).

  • Darwin: processes are created with posix_spawn(2), the only fork-safe primitive Apple supports for multithreaded programs; the kernel handles the intermediate child state, so pthread_atfork handler deadlocks and copy-on-write stalls are avoided entirely. posix_spawn is reached through a direct libSystem call (the same mechanism the Go runtime itself uses), not cgo, so there is no cgo call overhead. The spawn attributes (POSIX_SPAWN_SETSIGDEF, SETSIGMASK, CLOEXEC_DEFAULT) are initialized once per pooled spawn state rather than per spawn, and CLOEXEC_DEFAULT guarantees that no file descriptor other than the requested stdio descriptors leaks into the child, again without syscall.ForkLock. A Spec with all-nil stdio also freezes its file actions, reducing a spawn to a single posix_spawn libc call plus the wait4.

On both platforms argv, envp, and auxiliary strings are marshaled into a pooled, reusable arena as NUL-terminated C strings referenced by raw pointers, so steady-state spawning performs no per-string heap allocations. A Cmd respawned through Cmd.Reset with a preset Env, and Spec.Run always, perform zero heap allocations per spawn.

Differences from os/exec

The API mirrors os/exec where practical, with deliberate deviations that keep the hot path allocation- and goroutine-free:

  • Stdin, Stdout, and Stderr are *os.File, not io.Reader/io.Writer. A nil field means /dev/null (a shared descriptor, opened once). Use os.Pipe for streaming; Cmd.Output and Cmd.CombinedOutput do this internally.
  • Environment entries are passed to the kernel as-is: duplicates are not deduplicated. If Env is nil, a snapshot of the current environment is taken once and cached process-wide: a caller that mutates the environment (os.Setenv et al) after a spawn has occurred must call InvalidateEnv for later nil-Env commands to observe the change.
  • Cmd.Process and Cmd.ProcessState are value fields, and a Cmd must not be copied after first use.
  • The child always starts with all signal dispositions reset to their defaults and an empty signal mask.

A Cmd must be returned to its pre-start state with Cmd.Reset before it can be started again, and its methods must not be called concurrently. For running the same command many times, Spec freezes the marshaled command at construction, spawns with zero allocations, and is safe for concurrent use.

The FASTEXEC_NO_CLEAR_SIGHAND environment variable (read once at startup) forces the Linux signal-mask fallback, for testing and triage.

Index

Constants

This section is empty.

Variables

View Source
var ErrProcessDone = errors.New("fastexec: process already finished")

ErrProcessDone reports that a Process has already finished and been reaped.

Functions

func InvalidateEnv

func InvalidateEnv()

InvalidateEnv discards the environment snapshot used for commands with a nil Env. A caller that mutates the process environment (os.Setenv, os.Unsetenv, os.Clearenv) after a spawn has occurred must call InvalidateEnv for later nil-Env commands to observe the change; explicit Env slices are unaffected.

Types

type Cmd

type Cmd struct {
	// Path is the path of the command to run.
	//
	// This is the only field that must be set to a non-zero value. If
	// Path is relative, it is evaluated relative to Dir.
	Path string

	// Args holds command line arguments, including the command as
	// Args[0]. If Args is empty, Path is used as the sole argument.
	Args []string

	// Env specifies the environment of the process. Each entry is of the
	// form "key=value". If Env is nil, the new process uses the current
	// process's environment (obtained via os.Environ, which allocates).
	// Entries are passed to the kernel verbatim; duplicates are not
	// deduplicated.
	Env []string

	// Dir specifies the working directory of the command. If Dir is
	// empty, the command runs in the calling process's current directory.
	Dir string

	// Stdin, Stdout, and Stderr specify the process's standard input,
	// output, and error. A nil field means the corresponding descriptor
	// is connected to /dev/null.
	Stdin  *os.File
	Stdout *os.File
	Stderr *os.File

	// Process is the underlying process, valid once Start has
	// succeeded. It is embedded by value so steady-state spawning
	// allocates nothing; take its address to call its methods
	// concurrently.
	Process Process

	// ProcessState contains information about the exited process,
	// populated by Wait (its Pid method reports zero until then). It is
	// embedded by value; [ExitError] carries its own copy.
	ProcessState ProcessState
	// contains filtered or unexported fields
}

Cmd represents an external command being prepared or run.

After Run, Start, Output, or CombinedOutput has been called, a Cmd must be returned to its pre-start state with Cmd.Reset before it can spawn again. A Cmd must not be copied after first use: it embeds the process handle and its synchronization state by value.

func Command

func Command(name string, arg ...string) *Cmd

Command returns a Cmd to execute the named program with the given arguments, following the same PATH-resolution rules as os/exec.Command.

func CommandContext

func CommandContext(ctx context.Context, name string, arg ...string) *Cmd

CommandContext is like Command but includes a context.

The provided context is used to kill the process (with SIGKILL) if the context becomes done before the command completes on its own. On Linux the kill is delivered through the process's pidfd and can never affect a recycled PID.

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() ([]byte, error)

CombinedOutput runs the command and returns its combined standard output and standard error.

func (*Cmd) Output

func (c *Cmd) Output() ([]byte, error)

Output runs the command and returns its standard output. If the command exits with a non-zero status and c.Stderr was nil, the returned *ExitError retains up to 32 KiB of the standard error output in its Stderr field.

func (*Cmd) Reset

func (c *Cmd) Reset()

Reset returns c to its pre-start state so the same Cmd can spawn again, keeping the command configuration (Path, Args, Env, Dir, stdio, context) and the marshaling state. Together with a preset Env this makes repeated Run loops allocation-free.

Reset must not be called while a process started from c is still running. An ExitError returned by a previous run carries its own copy of the process state and stays valid across Reset.

func (*Cmd) Run

func (c *Cmd) Run() error

Run starts the specified command and waits for it to complete.

func (*Cmd) Start

func (c *Cmd) Start() error

Start starts the specified command but does not wait for it to complete.

After a successful call to Start the Cmd.Wait method must be called in order to release associated system resources.

func (*Cmd) String

func (c *Cmd) String() string

String returns a human-readable description of c. It is intended only for debugging.

func (*Cmd) Wait

func (c *Cmd) Wait() error

Wait waits for the command to exit. It must have been started by Cmd.Start.

If the command runs and exits with a non-zero status, the error is of type *ExitError. If the command was killed because its context became done, the context's error is returned instead.

type Error

type Error struct {
	// Name is the file name for which the error occurred.
	Name string
	// Err is the underlying error.
	Err error
}

Error is returned by Cmd.Start and [LookPath]-time failures when a command cannot be started.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

type ExitError

type ExitError struct {
	ProcessState

	// Stderr holds the standard error output of the command if it was
	// captured by [Cmd.Output] and the command's Stderr was nil.
	Stderr []byte
}

ExitError reports an unsuccessful exit by a command. It embeds its own copy of the final ProcessState, so it remains valid after the originating Cmd is reset or reused.

func (*ExitError) Error

func (e *ExitError) Error() string

Error implements the error interface.

type Process

type Process struct {
	// Pid is the process ID of the child.
	Pid int
	// contains filtered or unexported fields
}

Process represents a running process created by Cmd.Start.

All signaling goes through the process's pidfd, so a Process can never signal an unrelated process even if the kernel recycles the PID.

func (*Process) Kill

func (p *Process) Kill() error

Kill causes the process to exit immediately (unix.SIGKILL).

func (*Process) Signal

func (p *Process) Signal(sig unix.Signal) error

Signal sends sig to the process through its pidfd.

func (*Process) Wait

func (p *Process) Wait(ps *ProcessState) error

Wait blocks until the process exits, stores its final state into ps, and releases the process handle. It returns an *ExitError if the process exited unsuccessfully. Wait must be called exactly once per started process; it is used with Spec.Start, while Cmd.Wait wraps it with the Cmd bookkeeping.

type ProcessState

type ProcessState struct {
	// contains filtered or unexported fields
}

ProcessState stores information about a process, as reported by Wait.

func (*ProcessState) ExitCode

func (p *ProcessState) ExitCode() int

ExitCode returns the exit code of the exited process, or -1 if the process was terminated by a signal.

func (*ProcessState) Exited

func (p *ProcessState) Exited() bool

Exited reports whether the program has exited (as opposed to being terminated by a signal).

func (*ProcessState) Pid

func (p *ProcessState) Pid() int

Pid returns the process id of the exited process.

func (*ProcessState) String

func (p *ProcessState) String() string

String returns a human-readable description of the exit state.

func (*ProcessState) Success

func (p *ProcessState) Success() bool

Success reports whether the program exited successfully, such as with exit status 0 on Unix.

func (*ProcessState) Sys

func (p *ProcessState) Sys() unix.WaitStatus

Sys returns the system-dependent exit information about the process as a syscall.WaitStatus.

func (*ProcessState) SysUsage

func (p *ProcessState) SysUsage() *unix.Rusage

SysUsage returns the system-dependent resource usage information about the exited process.

type Spec

type Spec struct {
	// contains filtered or unexported fields
}

Spec is a frozen command: the path (resolved through PATH once, like Command), argv, environment, and working directory are marshaled into a retained arena at construction, so spawning performs no PATH lookup, no marshaling, and no heap allocation at all. On Darwin a Spec spawned with all-nil stdio additionally uses a file-actions object frozen at construction, reducing the spawn to a single posix_spawn libc call.

Unlike a Cmd, a Spec is immutable after construction and safe for concurrent use by multiple goroutines. It is intended for hot loops and worker pools that run the same command many times.

func NewSpec

func NewSpec(name string, args []string, env []string, dir string) (*Spec, error)

NewSpec freezes the named program with the given arguments, environment, and working directory.

Name resolution follows Command: a name without path separators is resolved through PATH once, here. args does not include argv[0]; the name is used, as with Command. A nil env freezes a snapshot of the current environment (via the same cache as a nil Cmd.Env); an empty dir inherits the parent's working directory.

func (*Spec) Run

func (s *Spec) Run(stdin, stdout, stderr *os.File, ps *ProcessState) error

Run spawns the frozen command, waits for it to complete, and stores the final state into ps. Like Cmd.Run it returns an *ExitError for an unsuccessful exit.

Run reaps the child directly rather than through a Process handle (whose signal-safety mutex would force a heap allocation), so it performs zero heap allocations on the success path.

func (*Spec) Start

func (s *Spec) Start(stdin, stdout, stderr *os.File, p *Process) error

Start spawns the frozen command with the given stdio streams (nil means /dev/null), filling in p, which must be in its zero or reset state. After a successful Start the caller must call Process.Wait to reap the child and release its resources. Callers that never signal the child should prefer Spec.Run, which bypasses the Process handle entirely.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL