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 关注
- 161 浏览
添加回答
举报