I want to capture the Ctrl+C (SIGINT
) signal sent from the console and print out some partial run totals.
Is this possible in Golang?
Note: When I first posted the question I was confused about Ctrl+C being SIGTERM
instead of SIGINT
.
I want to capture the Ctrl+C (SIGINT
) signal sent from the console and print out some partial run totals.
Is this possible in Golang?
Note: When I first posted the question I was confused about Ctrl+C being SIGTERM
instead of SIGINT
.
To add slightly to the other answers, if you actually want to catch SIGTERM (the default signal sent by the kill command), you can use
syscall.SIGTERM
in place of os.Interrupt. Beware that the syscall interface is system-specific and might not work everywhere (e.g. on windows). But it works nicely to catch both:All of the above seem to work when spliced in, but gobyexample's signals page has a really clean and complete example of signal capturing. Worth adding to this list.
Death is a simple library that uses channels and a wait group to wait for shutdown signals. Once the signal has been received it will then call a close method on all of your structs that you want to cleanup.
There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.
You can use the os/signal package to handle incoming signals. ^C is SIGINT, so you can use this to trap
os.Interrupt
.The manner in which you cause your program to terminate and print information is entirely up to you.
You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.
I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.
https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go
You can do this in a 'defer' fashion.
example for shutting down a server gracefully :