2020年10月16日 星期五

[ 文章收集 ] Go by Example: Signals

 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
  1. package main  
  2.   
  3. import (  
  4.     "fmt"  
  5.     "os"  
  6.     "os/signal"  
  7.     "syscall"  
  8. )  
  9.   
  10. func main() {  
  11.   
  12.     sigs := make(chan os.Signal, 1)  
  13.     done := make(chan bool, 1)  
  14.   
  15.     signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)  
  16.   
  17.     go func() {  
  18.         sig := <-sigs  
  19.         fmt.Println()  
  20.         fmt.Println(sig)  
  21.         done <- true  
  22.     }()  
  23.   
  24.     fmt.Println("awaiting signal")  
  25.     <-done  
  26.     fmt.Println("exiting")  
  27. }  
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
signal.Notify registers the given channel to receive notifications of the specified signals.

* Line17-21
This goroutine executes a blocking receive for signals. When it gets one it’ll print it out and then notify the program that it can finish.

* Line24-26
The program will wait here until it gets the expected signal (as indicated by the goroutine above sending a value on done) and then exit.


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:
$ go run signals.go
awaiting signal
^C
interrupt
exiting


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...