Skip to content

Instantly share code, notes, and snippets.

@reiki4040
Created October 2, 2014 14:38
Show Gist options
  • Star 68 You must be signed in to star a gist
  • Fork 23 You must be signed in to fork a gist
  • Save reiki4040/be3705f307d3cd136e85 to your computer and use it in GitHub Desktop.
Save reiki4040/be3705f307d3cd136e85 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)
}
@tronch0
Copy link

tronch0 commented Oct 16, 2017

Excellent example, helped me a lot :)

@haidlir
Copy link

haidlir commented Jul 15, 2018

Thanks, It helped me too..

@shsh24
Copy link

shsh24 commented Jul 25, 2018

nice example

@shangzongyu
Copy link

Thanks

@HubCodes
Copy link

Thank you for concise example

@ZZZeno
Copy link

ZZZeno commented Sep 21, 2020

Thanks, that fits for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment