HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
capturepossiblerunfashioncleanupfunctionsigintanddeferctrl

Problem

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.

Code Snippets

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

Context

Stack Overflow Q#11268943, score: 359

Revisions (0)

No revisions yet.