I tried to call some external commands non-blocking in Golang, so I used
cmd.Start()
and
go cmd.Wait()
Although I don't need to wait for the command to run successfully, the reason I run cmd.wait()
is because the document mentions Wait releases any resources associated with the Cmd."
So I don't want to cause a resource leak.
However, this usage will cause linter to report an error, reminding me that I have not handled the error.
Error return value of `cmd.Wait` is not checked (errcheck)
go cmd.Wait()
How do I handle error for go cmd.Wait()
? Or, if I don't run go cmd.Wait()
, will it cause a resource leak?
add:
One reason I use go cmd.Wait()
is that if I don't use it, the external process I started will become a zombie process when it is exited. I haven't figured out why this is happening.
Why do you want to run cmd.Wait()
as a goroutine? And if you really need to do this in a goroutine then you can try something like this. Basically wrapping up the cmd.Wait()
command inside an inline go func
go func(){
_ := cmd.Wait()
}()
You can do an error check also inside the go function.
If "cmd" goes out of scope the garbage collector will free its reference.
func execCommand() {
exec.Command("something").Start()
}
func main() {
execCommand()
time.Sleep(time.Minute * 1)
}
So something like this will have its resource freed when the command is executed exec.Wait command is used to get the exit code and waits for copying from stdout or something like that.
If you still wanna use cmd.Wait you have to start it as a seperate Function or you could just use exec.Run
go func(){
err := cmd.Run() //or cmd.Wait()
if err != nil {
fmt.println("error ", err)
}
}()