Golang Advanced (iii)--start and stop of background process

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

+++
Title= "Golang (three)--start and stop of background process"
Date= "2017-10-12"
tags=["Golang", "Cobra"]
categories=["Resource Management"]
Description= "no longer like Java or other languages in order to manipulate the background program to write various scripts, this article is worth your look."
Featured=true
Image= "Img/201710/fengjing2.jpg"
+++

Don't want to be like Java or other languages in order to manipulate the background program to write various scripts, this article is worth your look

Start command

As in the previous article, let's start with a non-background run command

func init() {    startCmd := &cobra.Command{        Use:   "start",        "Start Gonne",        func(cmd *cobra.Command, args []string) {            startHttp()        },    }    "deamon""d"false"is daemon?")    RootCmd.AddCommand(startCmd)}

Starthttp method to start an HTTP Web service

func startHttp() {    http.HandleFunc("/"func(w http.ResponseWriter, r *http.Request) {        "Hello cmd!")    })    if err := http.ListenAndServe(":9090"nilnil {        log.Fatal("ListenAndServe: ", err)    }}

Now gonne start you can start a Web service, but the program stays on the command line, and if the CTRL + C program terminates

Command-line arguments

If you want to start in the background, you have to let the start command know that it is running in the background, the way to refer to the Docker command line is to add-D, to give a command to determine the parameters only a few code

Change the code.

func init() {    varbool    startCmd := &cobra.Command{        Use:   "start",        "Start Gonne",        func(cmd *cobra.Command, args []string) {            if daemon {        fmt.Println("gonne start",daemon)                    }            startHttp()        },    }    "deamon""d"false"is daemon?")    RootCmd.AddCommand(startCmd)}

Command Line Input

-d

So you can receive the-D parameter, here to illustrate, the first parameter value, the second parameter code --deamon , the third parameter represents -d
, the fourth parameter code does not add a-D default value, and the five parameter is a description

Running in the background

The background is actually used here is a clever way, is to use the system command line to start their own command line input, is not a bit around, and then look at the modified code

run: func  (cmd *cobra. command, args []string ) {if  daemon {command: = Exec. Command ( "Gonne" , ) 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 ()},  

Using the EXEC command to start the input gonne start -d , it will intercept the request and then pass gonne start , but the program will not stay on the command line, and then found that the HTTP service is still available, and can be accessed.

The other thing is to put the PID output to the Gonne.lock file, to stop the program call

Terminate background program

It's a lot easier to stop when you have a previous operation.

func init() {    RootCmd.AddCommand(stopCmd)}var stopCmd = &cobra.Command{    Use:   "stop",    "Stop Gonne",    func(cmd *cobra.Command, args []string) {        strb, _ := ioutil.ReadFile("gonne.lock")        command := exec.Command("kill"string(strb))        command.Start()        println("gonne stop")    },}

Execute gonne stop to terminate the HTTP service that was started before

Help command

Well, the operation on the command is done, and then look at the benefits that Cobra gives, the auto-generated help command

This does not require you to do anything, only need to enter Gonne help , the relevant information has helped you to produce.

appletekiMacBook-Pro:andev apple$ gonne helpUsage:  gonne [flags]  gonne [command]Available Commands:  help        anycommand  start       Start Gonne  stop        Stop Gonne  version     theversionnumberof GonneFlags:  --help   help for gonne"gonne [command] --help"foracommand.

Of course, the subcommands also have

start -hStart GonneUsage:  gonne start [flags]Flags:  -d, --deamon   is daemon?  -h, --help     help for start

Farewell to the various scripts from this

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.