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