GO - Reading from Stdout in a loop

120

Question: GO - Reading from Stdout in a loop

I'm new to GO and I'm trying to write a small utility in which I would like to execute commands in a loop and read their output. The code works but only the first iteration produces an output. I guess the assignment of stdout in the first iteration somehow blocks the subsequent use of stdout. Can someone explain me how to get around this problem? (I simplified the code where the IP Addresses come from. I read them from a file but that's not relevant for the Problem.)

package main  import (     "os/exec"     "bufio"     "fmt"     "os"     "strings" )  var ip_addresses []string  func main() {     ip_addresses = append(ip_addresses,"/server:192.168.100.1")     ip_addresses = append(ip_addresses,"/server:192.168.100.2")     ip_addresses = append(ip_addresses,"/server:192.168.100.3")      for _, eachline := range ip_addresses {         if strings.HasPrefix(eachline, "#") != true {              c, b := exec.Command("query", "user", eachline), new(strings.Builder)             c.Stdout = b             c.Run()             print(b.String())         }     } } 

Total Answers: 1

42

Answers 1: of GO - Reading from Stdout in a loop

You should catch the *exec.ExitError exception and log it to prevent the loop from breaking.

for _, eachline := range ip_addresses {     cmd := exec.Command("ping", eachline)     stdout, err := cmd.Output()      if exit, ok := err.(*exec.ExitError); ok {         if status, ok := exit.Sys().(syscall.WaitStatus); ok {             log.Printf("Exit Status: %d", status.ExitStatus())         }     } else {         log.Fatal(err)     }     fmt.Print(string(stdout)) }