Skip to content

Instantly share code, notes, and snippets.

@naotookuda
Created April 9, 2019 00:48
Show Gist options
  • Save naotookuda/4d097b1a1cac6cabb927aaa4c686bc42 to your computer and use it in GitHub Desktop.
Save naotookuda/4d097b1a1cac6cabb927aaa4c686bc42 to your computer and use it in GitHub Desktop.
Handle OS signal on golang
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
// ExitCode is process exit code to os
type ExitCode int
// Process exsit codes
const (
Error ExitCode = 1
Critical ExitCode = 128
)
func criticalExitCode(s syscall.Signal) ExitCode {
r := ExitCode(int(Critical) + int(s))
return r
}
func main() {
signalc := make(chan os.Signal, 1)
signal.Notify(signalc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
exitc := make(chan ExitCode)
go func() {
for {
s := <-signalc
switch s {
// kill -SIGHUP XXXX
case syscall.SIGHUP:
fmt.Println("SIGHUP")
exitc <- criticalExitCode(syscall.SIGHUP)
// kill -SIGINT XXXX or Ctrl+c
case syscall.SIGINT:
fmt.Println("SIGINT")
exitc <- criticalExitCode(syscall.SIGINT)
// kill -SIGTERM XXXX
case syscall.SIGTERM:
fmt.Println("SIGTERM")
exitc <- criticalExitCode(syscall.SIGTERM)
// kill -SIGQUIT XXXX
case syscall.SIGQUIT:
fmt.Println("SIGQUIT")
exitc <- criticalExitCode(syscall.SIGQUIT)
default:
fmt.Println("UNKNOWN SIGNAL")
exitc <- Error
}
}
}()
code := <-exitc
os.Exit(int(code))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment