Skip to content

Instantly share code, notes, and snippets.

@tsdtsdtsd
Forked from reiki4040/signal.go
Created November 25, 2017 11:41
Show Gist options
  • Save tsdtsdtsd/1d381ddc6060be40ba8c20af38028413 to your computer and use it in GitHub Desktop.
Save tsdtsdtsd/1d381ddc6060be40ba8c20af38028413 to your computer and use it in GitHub Desktop.
signal handling example for golang
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
signal_chan := make(chan os.Signal, 1)
signal.Notify(signal_chan,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
exit_chan := make(chan int)
go func() {
for {
s := <-signal_chan
switch s {
// kill -SIGHUP XXXX
case syscall.SIGHUP:
fmt.Println("hungup")
// kill -SIGINT XXXX or Ctrl+c
case syscall.SIGINT:
fmt.Println("Warikomi")
// kill -SIGTERM XXXX
case syscall.SIGTERM:
fmt.Println("force stop")
exit_chan <- 0
// kill -SIGQUIT XXXX
case syscall.SIGQUIT:
fmt.Println("stop and core dump")
exit_chan <- 0
default:
fmt.Println("Unknown signal.")
exit_chan <- 1
}
}
}()
code := <-exit_chan
os.Exit(code)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment