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

Issue

I want to capture the Ctrl+C (SIGINT) signal sent from the console and print out some partial run totals.

Solution

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.

Answered By – Lily Ballard

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.