1

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 ?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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()
    }()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.