Does anyone know how to run detached command in golang (Go)?
Task is: I have app1 and app2, app2 do big, long job, approx. 2 hrs. But app1 is default app which do its job in minutes, called frequently, 1-2 times per day. Practically, I need to run app1, than run app2 in app1 gorutine, app1 will finish its job and close, but app2 must still work until end of its tasks list. So could be normal situation if 2-3 app2 instances runned.
I need smth. like this, what I do in bash:
$ ./my-app &
...or in Qt:
QProcess prc;
prc.setArguments(args);
prc.setProgram(app2);
prc.setWorkingDirectory(dir);
prc.startDetached();
Qt doc:
bool QProcess::startDetached(qint64 *pid = nullptr)
Starts the program with arguments in a new process, and detaches from it ... If the calling process exits, the detached process will continue to run unaffected. The started process will run in its own session and act like a daemon. If the function is successful then *pid is set to the process identifier of the started process. Note that the child process may exit and the PID may become invalid without notice. Furthermore, after the child process exits, the same PID may be recycled and used by a completely different process.
So, I do it like this in Go:
cmd := exec.Command("./app2", "&")
_ = cmd.Run()
...but it isn't helps, 'app2' still is not detached. And if I kill main app1 from where run 'app2', than 'app2' also will be closed.
Also I tried this way: (in app1)
var attr = os.ProcAttr{
Dir: ".",
Env: os.Environ(),
Files: []*os.File{
os.Stdin,
os.Stdout,
os.Stderr,
},
}
process, err := os.StartProcess(server, []string{"/usr/local/app2"}, &attr)
if err == nil {
err = process.Release()
}
if err != nil {
log.Println(err)
}
and can tell, it also doesn't work.
For now I have only one solution: make app2 as server, with ListenAndServe and than in app1 run app2 no metter how, but in gorutine:
go func() {
cmd := exec.Command("/usr/local/app2")
_ = cmd.Run()
}()
and run app1 in bash as detached process:
./app1 &
in this case app1 will run app2, will do all its work and closes, but app2 will do all its long work.
Actually, I want to do in golang (Go language) the same what I do with QProcess::startDetached in Qt (cross-platform application development framework used to extend the C++ language)
PS. Golang (or Go, for grammar-nazis who have a heart attack in case of using Golang word): BTW, "many use the golang name, though, and it is handy as a label" https://golang.org/doc/faq#go_or_golang