Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

Sebastián Grignoli picture Sebastián Grignoli · Jun 29, 2012 · Viewed 99.8k times · Source

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.

Answer

Lily Ballard picture Lily Ballard · Jun 29, 2012

You can use the os/signal package to handle incoming signals. Ctrl+C is SIGINT, so you can use this to trap os.Interrupt.

c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func(){
    for sig := range c {
        // sig is a ^C, handle it
    }
}()

The manner in which you cause your program to terminate and print information is entirely up to you.