Go语言daemon启动本身.实现

前端之家收集整理的这篇文章主要介绍了Go语言daemon启动本身.实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. package main
  1.  
  1. import (
  1. "fmt"
  1. "log"
  1. "net/http"
  1. "os"
  1. "os/signal"
  1. "syscall"
  1. )
  1.  
  1. func main() {
  1. File,err := os.Create("log")
  1. if err != nil {
  1. fmt.Println("创建日志文件错误",err)
  1. return
  1. }
  1. log.SetOutput(File)
  1. ce("pid")
  1. }
  1.  
  1. func ce(pid string) {
  1. File,err := os.OpenFile(pid,os.O_RDWR|os.O_CREATE,0644)
  1. if err != nil {
  1. log.Println(err)
  1. return
  1. }
  1. info,_ := File.Stat()
  1. if info.Size() != 0 {
  1. log.Println("pid file is exist")
  1. return
  1. }
  1. if os.Getppid() != 1 {
  1. args := append([]string{os.Args[0]},os.Args[1:]...)
  1. os.StartProcess(os.Args[0],args,&os.ProcAttr{Files: []*os.File{os.Stdin,os.Stdout,os.Stderr}})
  1. return
  1. }
  1. File.WriteString(fmt.Sprint(os.Getpid()))
  1. c := make(chan os.Signal,1)
  1. signal.Notify(c,os.Interrupt,syscall.SIGUSR2)
  1. go HttpServer()
  1. for {
  1. s := <-c
  1. switch s {
  1. case syscall.SIGUSR2:
  1. fmt.Println("自定义型号.")
  1. case os.Interrupt:
  1. fmt.Println("安全退出")
  1. Exit(File)
  1. }
  1. }
  1. }
  1.  
  1. func HttpServer() {
  1. http.HandleFunc("/",route)
  1. http.ListenAndServe(":1789",nil)
  1. }
  1.  
  1. func route(w http.ResponseWriter,r *http.Request) {
  1. log.Println(r.URL.Path)
  1. fmt.Fprint(w,"Hello World\n")
  1. }
  1. func Exit(F *os.File) {
  1. F.Close()
  1. os.Remove(F.Name())
  1. fmt.Println("bye")
  1. }

猜你在找的Go相关文章