Does a deferred Restore() run if you ctrl-c out of an app?

Viewed 360

In Go, you have something like:

func main() {
 defer func() {
        if r := recover(); r != nil {
            /*run some clean up code here...*/
            fmt.Println("Recovered")
        }
    }()

 /*Some code right here like a web server that runs until panic or ctrl-c'd out */

}

If I ctrl-C in Linux, will it run the defer? Or does it immediately exit? If it immediately exits, is there a way around that? A way to run code, no matter what, on exit of the app?

1 Answers

Ctrl-C or another signal will terminate the program without calling deferred functions. You can catch ctrl-c using a signal handler. Read the documentation for the os/signal package, it has OS specific behavior. Something like below would catch ctrl-c:

    c := make(chan os.Signal, 1)
    signal.Notify(c,os.Interrupt)
    go func() {
        s := <-c
        // signal caught, cleanup
    }()
Related