golang实现daemon守护进程,支持goroutine和系统信号监听
网上看了好多解决方案,要不就是不支持goroutine, 要不就是不支持系统信号监听。自己尝试了一下,算是可以是满足需求了
package main
import (
"os"
"fmt"
"os/signal"
"syscall"
"time"
"log"
"os/exec"
)
func init() {
if os.Getppid() != 1{
cmd := exec.Command(os.Args[0], os.Args[1:]...)
cmd.Start()
os.Exit(0)
}
// 监听系统信号
go func() {
_c := make(chan os.Signal, 1)
signal.Notify(_c, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL, syscall.SIGTSTP)
msg := <- _c
log.Println(msg)
os.Exit(0)
}()
}
func main() {
go func(){
fp, _ := os.OpenFile("log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
log.SetOutput(fp)
for{
log.Println(fmt.Sprint("hello ", os.Getpid()))
time.Sleep(time.Second * 5)
}
}()
for{
time.Sleep(time.Second * 1000)
}
}