有時我們希望Go程序能夠智能地處理Unix信號。 例如,可能希望服務(wù)器在接收到SIGTERM時正常關(guān)閉,或者在收到SIGINT時使用命令行工具停止處理輸入。下面介紹如何使用Go語言處理信號。
Go信號通知通過在通道上發(fā)送os.Signal值來工作。創(chuàng)建一個通道來接收這些通知(還會在程序退出時通知我們)。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請參考:http://www.yiibai.com/go/go_environment.html
signal.go的完整代碼如下所示 -
package main
import "fmt"
import "os"
import "os/signal"
import "syscall"
func main() {
// 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).
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
// `signal.Notify` registers the given channel to
// receive notifications of the specified signals.
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// 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.
go func() {
sig := <-sigs
fmt.Println()
fmt.Println(sig)
done <- true
}()
// 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.
fmt.Println("awaiting signal")
<-done
fmt.Println("exiting")
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run signal.go
awaiting signal
[Ctl+C]
interrupt
exiting