/**
Go 语言中实现优雅的停止程序
主goroutine监听操作系统消息,收到系统停止消息后关闭server的chan,所有子协程检测到chan关闭,则全部退出
**/
package main
import (
"log"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
// An uninteresting service.
type Service struct {
ch chan bool
waitGroup *sync.WaitGroup
}
// Make a new Service.
func NewService() *Service {
return &Service{
ch: make(chan bool),
waitGroup: &sync.WaitGroup{},
}
}
// Accept connections and spawn a goroutine to serve each one. Stop listening
// if anything is received on the service's channel.
func (s *Service) Serve(listener *net.TCPListener) {
s.waitGroup.Add(1)<