首页 ? golang(go语言) ? golang实现接受命令行参数并运行到后台的案例(类似nginx -s reload|stop)

golang实现接受命令行参数并运行到后台的案例(类似nginx -s reload|stop)

添加评论 次下载365游戏棋牌游戏_365棋牌辅助透视好用吗_365手游棋牌免费送金币

【提示】 非法信息举报请联系本站小编 QQ:5.4069748.5

使用golang编译的程序,接受命令行参数,并且实现类似nginx启动和重载的命令
package main

import (
"log"
"os"
"github.com/valyala/fasthttp"
"flag"
"os/exec"
"io/ioutil"
"fmt"
)

var (
operation = flag.String("s",""," main -s start|stop|restart ")
)

func main() {
flag.Parse()

if _, err := os.Stat("conf/"); err != nil {
log.Panic("配置目录不存在 conf/ rn")
}
if _, err := os.Stat("conf/config.json"); err != nil {
log.Panic("配置文件不存在 conf/config.json rn")
return
}

if _, err := os.Stat("logs/"); err != nil {
os.Mkdir("logs/", 0666)
}

if *operation == "" {
cmd := exec.Command(os.Args[0],"-s","start")
err := cmd.Start()
if err != nil {
log.Panic(err)
}
}else if *operation == "start"{
log.Println("启动")
start()
}else if *operation == "stop" {
stop()
}else if *operation == "restart" {
stop()
cmd := exec.Command(os.Args[0],)
cmd.Start()
}
}

func start() {
err := ioutil.WriteFile("logs/www.bingfengsa.com.pid",[]byte(fmt.Sprintf("%d",os.Getpid())),0666)
if err != nil {
log.Printf("pid文件写入失败,%sn",err.Error())
return
}

config.LoadConfig("conf/config.json")
//defer config.Destruct()

handle := func(ctx *fasthttp.RequestCtx) {
router.Handle(ctx)
}
if err := fasthttp.ListenAndServe(":8080", handle); err != nil {
log.Fatalf("Error in ListenAndServe: %s", err)
} else {
log.Printf("Server Start at port:8080")
}
}

func stop() {
content,err := ioutil.ReadFile("logs/www.bingfengsa.com.pid")
os.Remove("logs/www.bingfengsa.com.pid")
if err == nil && len(content) != 0 {
pid := string(content)
cmd :=exec.Command("kill",pid)
cmd.Run()
}
}