Reputation: 617
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.
Upvotes: 0
Views: 1184
Reputation: 5049
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)
Upvotes: 1
Reputation: 273496
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.
Upvotes: 2