Created
April 9, 2019 00:48
-
-
Save naotookuda/4d097b1a1cac6cabb927aaa4c686bc42 to your computer and use it in GitHub Desktop.
Handle OS signal on golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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