os.Exit Skips Deferred Functions
Register a deferred cleanup and call os.Exit to prove the deferred function never runs: exit terminates the process immediately.
Code
package main
import (
"fmt"
"os"
)
// worker 正常返回:deferred 清理按 LIFO 执行
func worker() {
defer fmt.Println("worker defer: runs on normal return")
fmt.Println("worker: done")
}
func main() {
worker()
// os.Exit 立即终止进程,deferred 函数永远不执行
defer fmt.Println("cleanup: never printed")
fmt.Println("work finished, exiting")
os.Exit(0)
}How the code moves
os.Exit Skips Deferred Functions is built around the functions worker and main.
Cleanup is attached with defer, so it runs when worker returns normally — but the defer registered in main right before os.Exit never runs at all.
Points of care
- No package manager involved — every call resolves to a built-in API.
Putting it to use
Signature: func worker()
The run emits 3 labeled sections — worker: done, worker defer: runs on normal return, work finished, exiting; cleanup: never printed is the one registered line that never appears, because os.Exit skips deferred functions.
The demo flow inside main is worker — run the file to see it end to end.
Core lines
func worker() {
defer fmt.Println("worker defer: runs on normal return")
fmt.Println("worker: done")
}
func main() {
worker()
// os.Exit 立即终止进程,deferred 函数永远不执行
defer fmt.Println("cleanup: never printed")
fmt.Println("work finished, exiting")
os.Exit(0)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does os.Exit Skips Deferred Functions print when run?
- No setup needed: run the file and look for labeled lines like `worker defer: runs on normal return`, `worker: done`, `cleanup: never printed` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.