简体   繁体   中英

What is a good way to start another instance of the running program using Golang?

I would like a Go program to start multiple processes which it will interact with. (I'm also undecided on what method of IPC to use, but perhaps that's another question)

On thing I've thought of is using os.Executable() to get the location of the running executable, and then the exec package to run a new instance of the program. I wonder if there's another way to do this without needing to query the path of the executable, or if this is even a behaviour I should worry about.

Using os.Executable is the recommended way to find your program's own path in recent version of Go ( see this older SO answer for details ). And then you can use exec.Command to run more instances of it.

It's rather unusual though, so I wonder what use case you had in mind here. Orchestrating multiple processes is tricky and needs to solve a real issue for you to be worth it, in my experience.

You're right, to executes another instance of the running program you can use os.Executable() :

path, err := os.Executable()
if err != nil {
    log.Println(err)
}
cmd := exec.Command(path)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
    log.Println(err)
}

I'm not aware of your scenario, however doing this is not very common.

Unless you're thinking in create child (á la fork/exec) so maybe you'll need to pass extra file descriptors using cmd.ExtraFiles to the child and a combination of signal exchanges to creates child or terminates parent (usually SIGUSR1 and SIGTERM)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM