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 Runner 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 Runner.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, Runner 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 ¶
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 ¶
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 ¶
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 ¶
CombinedOutput runs the command and returns its combined standard output and standard error.
func (*Cmd) Output ¶
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) Start ¶
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 ¶
String returns a human-readable description of c. It is intended only for debugging.
func (*Cmd) Wait ¶
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.
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.
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 ¶
Kill causes the process to exit immediately (unix.SIGKILL).
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 Runner.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 Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner 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 Runner 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 Runner 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 NewRunner ¶
NewRunner 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 (*Runner) Run ¶
func (s *Runner) 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 (*Runner) Start ¶
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 Runner.Run, which bypasses the Process handle entirely.