Jacob Tomlinson's profile picture Jacob Tomlinson
Home Blog Talks About

Golang block until interrupt with ctrl+c

1 minute read #golang, #snippet

Today I found myself needing a Go application’s main thread to stop and wait until the user wants it to exit with a ctrl+c keyboard interrupt.

To do this we can use the os/signal package to put signals into a channel, and then block until that channel receives a signal.

import (
  "fmt"
  "os"
  "os/signal"
  "syscall"
)

func init() {
  done := make(chan os.Signal, 1)
  signal.Notify(done, syscall.SIGINT, syscall.SIGTERM)
  fmt.Println("Blocking, press ctrl+c to continue...")
  <-done  // Will block here until user hits ctrl+c
}

Have thoughts?

I love hearing feedback on my posts. You should head over to Twitter and let me know what you think!

Spotted a mistake? Why not suggest an edit!