How do I get results from Go exec.Command().Output() with commands that do not return immediately?

Viewed 251

I am using the answer in How do you get the output of a system command in Go? for a command that does not return immediately. My results look like a race condition. Here is the code:

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    date, err := exec.Command("date").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", date)

    ping, err := exec.Command("fping", "10.10.18.2", "-C10", "-q", "-e").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("ping has %d bytes and value [%s]\n", len(ping), ping)
}

Here is the output:

$ ./race
The date is Wed Dec  8 14:46:08 EST 2021

ping has 0 bytes and value []

Here is the output from the command line:

fping 10.10.18.2 -C10 -q -e
10.10.18.2 : 1.23 1.53 1.31 1.30 1.17 1.25 1.10 1.15 1.26 1.11

There is a pause after the output of the date command, but the result of the fping call is not included in the return value. Similar fping commands works great when I create a pipe to read from standard out and use cmd.Start() and cmd.Wait().

0 Answers
Related