Skip to content

Instantly share code, notes, and snippets.

@xordspar0
Last active March 18, 2020 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xordspar0/a2299f320bbe124a7b939e3a6456756d to your computer and use it in GitHub Desktop.
Save xordspar0/a2299f320bbe124a7b939e3a6456756d to your computer and use it in GitHub Desktop.

This little Go program does not run the defer statement when you interrupt by pressing ctrl-C:

package main

import "fmt"

func main() {
  defer fmt.Println("Shutting down...")

  for {
  }
}
> go run interrupt.go
^Csignal: interrupt
>

You have to actually trap the signal and handle it. Fortunately that’s super simple in Go:

package main

import "fmt"
import "os"
import "os/signal"

var shutdown = make(chan struct{})

func main() {
  defer fmt.Println("Shutting down...")

  go func () {
   waitForInterrupt := make(chan os.Signal, 1)
   signal.Notify(waitForInterrupt, os.Interrupt)
   <-waitForInterrupt
   close(shutdown)
  }()

  for {
   select {
   case <-shutdown:
    return
   default:
   }
  }
}
> go run trapped_interrupt.go
^CShutting down...
>

References

You can learn more about...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment