+++
title=”golang进阶(三)——后台进程的启动和停止”
date=”2017-10-12”
tags=[“golang”,”cobra”]
categories=[“资源管理”]
description=”不想再像java或者其他语言那样为了操作后台程序写各种脚本的话,这篇文章值得你一看”
featured=true
image=”img/201710/fengjing2.jpg”
+++
启动命令
title=”golang进阶(三)——后台进程的启动和停止”
date=”2017-10-12”
tags=[“golang”,”cobra”]
categories=[“资源管理”]
description=”不想再像java或者其他语言那样为了操作后台程序写各种脚本的话,这篇文章值得你一看”
featured=true
image=”img/201710/fengjing2.jpg”
+++
- func init() {
- startCmd := &cobra.Command{
- Use: "start",
- Short: "Start Gonne",serif; font-size:12px; line-height:1.8em"> Run: func(cmd *cobra.Command,args []string) {
- startHttp()
- },serif; font-size:12px; line-height:1.8em"> }
- startCmd.Flags().BoolVarP(&daemon,"deamon","d",false,"is daemon?")
- RootCmd.AddCommand(startCmd)
-
- }
- func startHttp() {
- http.HandleFunc("/",func(w http.ResponseWriter,r *http.Request) {
- fmt.Fprintf(w,"Hello cmd!")
- })
- if err := http.ListenAndServe(":9090",nil); err != nil {
- log.Fatal("ListenAndServe: ",err)
- 复制代码
现在通过gonne start便可以启动一个web服务了,但是程序停留在命令行,如果ctrl+C程序也会终止了
命令行参数
改造一下代码
- var daemon bool
- if daemon {
- fmt.Println("gonne start",daemon)
- }
- 命令行输入
后台运行
- Run: func(cmd *cobra.Command,serif; font-size:12px; line-height:1.8em"> if daemon {
- command := exec.Command("gonne","start")
- command.Start()
- fmt.Printf("gonne start,[PID] %d running...\n",command.Process.Pid)
- IoUtil.WriteFile("gonne.lock",[]byte(fmt.Sprintf("%d",command.Process.Pid)),0666)
- daemon = false
- os.Exit(0)
- } else {
- fmt.Println("gonne start")
- }
- startHttp()
- },
有了之前的操作后,停止就简单多了- RootCmd.AddCommand(stopCmd)
- var stopCmd = &cobra.Command{
- Use: "stop",serif; font-size:12px; line-height:1.8em"> Short: "Stop Gonne",serif; font-size:12px; line-height:1.8em"> strb,_ := IoUtil.ReadFile("gonne.lock")
- command := exec.Command("kill",string(strb))
- println("gonne stop")
- 执行 gonne stop 即可终止之前启动的http服务
这个不需要你做什么操作,只需要输入gonne help,相关信息已经帮你生产好了。- appletekiMacBook-Pro:andev apple$ gonne help
- Usage:
- gonne [flags]
- gonne [command]
- Available Commands:
- help Help about any command
- start Start Gonne
- stop Stop Gonne
- version Print the version number of Gonne
- Flags:
- -h,--help help for gonne
- Use "gonne [command] --help" for more information about a command.
- appletekiMacBook-Pro:andev apple$ gonne start -h
- Start Gonne
- gonne start [flags]
- -d,--deamon is daemon?
- 复制代码
- Run: func(cmd *cobra.Command,serif; font-size:12px; line-height:1.8em"> if daemon {