Details please see affected/package: exec, why output nothing? · Issue #55887 · golang/go · GitHub.
@Bill_Wang, thank you for joining the forum.
Have you tested the code without the goroutine? That is, let the code inside the anonymous func run directly in main.
My guess is that cmd.Wait() continues before the goroutine is able to read from stdout.
For other readers, this is the code in question:
package main
import (
"bufio"
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("mtr", "-p", "-c", "10", "www.qq.com")
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println(err)
}
if err := cmd.Start(); err != nil {
fmt.Println(err)
}
go func() {
scr := bufio.NewScanner(stdout)
for {
if scr.Scan() {
fmt.Println(scr.Text())
}
if scr.Err() != nil {
return
}
}
}()
if err := cmd.Wait(); err != nil {
fmt.Println(err)
}
}
1 Like
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.