2 回答

TA貢獻1784條經驗 獲得超7個贊
你可以這樣做:
package main
import (
"os"
"os/signal"
"syscall"
)
// We make sigHandler receive a channel on which we will report the value of var quit
func sigHandler(q chan bool) {
var quit bool
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
// foreach signal received
for signal := range c {
// logEvent(lognotice, sys, "Signal received: "+signal.String())
switch signal {
case syscall.SIGINT, syscall.SIGTERM:
quit = true
case syscall.SIGHUP:
quit = false
}
if quit {
quit = false
// closeDb()
// logEvent(loginfo, sys, "Terminating..")
// closeLog()
os.Exit(0)
}
// report the value of quit via the channel
q <- quit
}
}
func main() {
// init two channels, one for the signals, one for the main loop
sig := make(chan bool)
loop := make(chan error)
// start the signal monitoring routine
go sigHandler(sig)
// while vat quit is false, we keep going
for quit := false; !quit; {
// we start the main loop code in a goroutine
go func() {
// Main loop code here
// we can report the error via the chan (here, nil)
loop <- nil
}()
// We block until either a signal is received or the main code finished
select {
// if signal, we affect quit and continue with the loop
case quit = <-sig:
// if no signal, we simply continue with the loop
case <-loop:
}
}
}
但是請注意,該信號會導致主循環繼續,但不會停止在第一個 goroutine 上的執行。

TA貢獻1812條經驗 獲得超5個贊
這是一種結構化事物來做你想做的事情的方法,分離關注點,這樣信號處理代碼和主代碼是分開的,并且很容易獨立測試。
如何實現 Quit 和 ReloadConfig 完全取決于您的程序 - ReloadConfig 可能會在通道上向正在運行的 goroutine 發送“請重新加載”值;它可能會鎖定互斥鎖并更改一些共享配置數據;或其他一些可能性。
package main
import (
"log"
"os"
"os/signal"
"syscall"
)
func main() {
obj := &myObject{}
go handleSignals(obj)
select {}
}
type myObject struct {
}
func (obj *myObject) Quit() {
log.Printf("quitting")
os.Exit(0)
}
func (obj *myObject) ReloadConfig() {
log.Printf("reloading configuration")
}
type MainObject interface {
ReloadConfig()
Quit()
}
func handleSignals(main MainObject) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
for sig := range c {
switch sig {
case syscall.SIGINT, syscall.SIGTERM:
main.Quit()
return
case syscall.SIGHUP:
main.ReloadConfig()
}
}
}
- 2 回答
- 0 關注
- 193 瀏覽
添加回答
舉報