[Golang] Capture and Handle Ctrl+C Event


For database programs, we need to close the database if users press Ctrl+C to terminate the program. This post shows how to capture Ctrl+C event and run the handler in Go.

Souce Code

ctrl+c.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// http://stackoverflow.com/questions/11268943/golang-is-it-possible-to-capture-a-ctrlc-signal-and-run-a-cleanup-function-in
// https://gobyexample.com/signals
package main

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

func handleCtrlC(c chan os.Signal) {
	sig := <-c
	// handle ctrl+c event here
	// for example, close database
	fmt.Println("\nsignal: ", sig)
	os.Exit(0)
}

func main() {
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go handleCtrlC(c)

	// block here
	for { select {} }
}

Tested on: Ubuntu Linux 14.10, Go 1.4.


References:

[1]go - Golang: Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion? - Stack Overflow
[2]Go by Example: Signals
[3]Channels - A Tour of Go