2

[Golang] Capture and Handle Ctrl+C Event

 2 years ago
source link: http://siongui.github.io/2015/03/11/go-ctrl-c-handler/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

// 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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK