Source From Here
Preface
Sometimes we’d like our Go programs to intelligently handle Unix signals. For example, we might want a server to gracefully shutdown when it receives a SIGTERM, or a command-line tool to stop processing input if it receives a SIGINT. Here’s how to handle signals in Go with channels.
HowTo
Go signal notification works by sending os.Signal values on a channel. We’ll create a channel to receive these notifications (we’ll also make one to notify us when the program can exit).
* Line15
* Line17-21
* Line24-26
When we run this program it will block waiting for a signal. By typing ctrl-C (which the terminal shows as ^C) we can send a SIGINT signal, causing the program to print interrupt and then exit:
Sometimes we’d like our Go programs to intelligently handle Unix signals. For example, we might want a server to gracefully shutdown when it receives a SIGTERM, or a command-line tool to stop processing input if it receives a SIGINT. Here’s how to handle signals in Go with channels.
HowTo
- package main
- import (
- "fmt"
- "os"
- "os/signal"
- "syscall"
- )
- func main() {
- sigs := make(chan os.Signal, 1)
- done := make(chan bool, 1)
- signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
- go func() {
- sig := <-sigs
- fmt.Println()
- fmt.Println(sig)
- done <- true
- }()
- fmt.Println("awaiting signal")
- <-done
- fmt.Println("exiting")
- }
* Line15
* Line17-21
* Line24-26
When we run this program it will block waiting for a signal. By typing ctrl-C (which the terminal shows as ^C) we can send a SIGINT signal, causing the program to print interrupt and then exit:
沒有留言:
張貼留言