You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.2 KiB
55 lines
1.2 KiB
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
)
|
|
|
|
// 输入-d 参数,以守护进程方式运行
|
|
func isDaemon() bool {
|
|
for _, arg := range os.Args {
|
|
if arg == "-d" {
|
|
fmt.Println("以守护进程方式运行")
|
|
return true
|
|
}
|
|
}
|
|
fmt.Println("以非守护进程方式运行")
|
|
return false
|
|
}
|
|
|
|
// 优雅退出(退出信号)
|
|
func waitElegantExit(signalChan chan os.Signal) {
|
|
for i := range signalChan {
|
|
switch i {
|
|
case syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT:
|
|
// 这里做一些清理操作或者输出相关说明,比如 断开数据库连接
|
|
fmt.Println("receive exit signal ", i.String(), ",exit...")
|
|
os.Exit(0)
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println("JSON RPC服务端")
|
|
// 检查是否以守护进程方式运行
|
|
if isDaemon() {
|
|
// 以守护进程方式运行
|
|
}
|
|
// 优雅退出
|
|
// quit := make(chan os.Signal)
|
|
// signal.Notify(quit, os.Interrupt, os.Kill)
|
|
// v := <-quit
|
|
// fmt.Println("退出信号:", v)
|
|
|
|
c := make(chan os.Signal)
|
|
// SIGHUP: terminal closed
|
|
// SIGINT: Ctrl+C
|
|
// SIGTERM: program exit
|
|
// SIGQUIT: Ctrl+/
|
|
signal.Notify(c, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
|
|
|
|
// 阻塞,直到接受到退出信号,才停止进程
|
|
waitElegantExit(c)
|
|
}
|
|
|