I am a beginner in Go.
I would like to use the code snippet from : How would you define a pool of goroutines to be executed at once in Golang? (this answer)
I need to check the error for each cmd executed as in :
out, err := exec.Command(cmd,params).Output()
But, in the snippet there is no error checking:
tasks <- exec.Command("zenity", "--info", "--text='Hello from iteration n."+strconv.Itoa(i)+"'")
How can check for errors when the cmd executes ?
That line:
tasks <- exec.Command("zenity", "--info", "--text='Hello from iteration n."+strconv.Itoa(i)+"'")
is adding a Cmd
object into the channel, from where it will be pulled later and executed by this code:
for cmd := range tasks {
cmd.Run()
}
so it is here that you need to check the error code. Since you suggested you wanted to use Cmd.Output
instead of Run
, it would look like this:
for cmd := range tasks {
out, err := Cmd().Output()
}
You see, exec.Command
creates and initializes an object, and .Output
or .Run
tells that object to do its stuff.
exec.Command
doesn't execute the command, it creates a *Cmd
only.
You would check the err in the go func()
go func() {
for cmd := range tasks {
err := cmd.Run()
// do the test here
}
wg.Done()
}()