Common kill Signals and How to Catch Them in Go
Common kill signals for Go programs and how to catch them. Verified on MacOS, based on go1.17.7.
Copyright notice: This is an original article by xwi88, licensed under CC BY-NC 4.0. Commercial use is prohibited; please cite the source when reposting. Follow at https://github.com/xwi88
Common signals
| |
Go Code
| |
For a more convenient wrapper, see signal
kill testing
Run
killon the host to stop theapp. There are two runtime environments: host and docker.
Host
kill -<signal_number | signal_name> <pid>
kill defaults to signal_number=15 TERMTested — signals that can be caught normally and return 0:
1, 2, 3, 6, 14, 15,30, 31HUP, INT, QUIT, ABRT, ALRM, TERM, USR1, USR2- case-insensitive
SIGprefix allowed, also case-insensitive
docker
docker kill -<signal_number | signal_name> <container_id>
docker kill defaults to signal_number=9 KILLTested — signals that can be caught normally and return 0:
1, 2, 3, 6, 14, 15,10, 12- In testing,
docker killonly recognizes10and12asUSR1andUSR2 - Reason unclear;
USR1/USR2not recommended
- In testing,
HUP, INT, QUIT, ABRT, ALRM, TERM, USR1, USR2- case-insensitive
SIGprefix allowed, also case-insensitive
Conclusion
From the tests above, the commonly catchable, no-difference, return-0 signals are:
1, 2, 3, 6, 14, 15
By signal semantics, we recommend using:
- 2 SIGINT — trigger:
CTRL+Corkill -2 - 15 SIGTERM
Graceful shutdown
- Send
killwith-15/-TERM/-SIGTERM - After the program catches the signal: remove the node from discovery, release resources, stop the program
- After a configured interval, check whether it stopped; if not, fall back to
kill -9/-KILL/-SIGKILLper your policy
k8s graceful shutdown
- Remove the node
preStop hookoptional delay, to drain in-flight traffic- Send
killwith-15/-TERM/-SIGTERM - The program catches the signal, releases resources, stops
- Force-killed on timeout via
kill -9/-KILL/-SIGKILL- default 30s
- pod:
terminationGracePeriodSecondsto change it
Docker-compose kill issue
- Current
Docker Compose version 2.2.2
docker-compose may fail to stop on CTRL+C; force quit with CTRL+\