Friday, April 26, 2024
HomeGolangExec, why output nothing? - Getting Assist

Exec, why output nothing? – Getting Assist


Particulars please see affected/package deal: exec, why output nothing? · Situation #55887 · golang/go · GitHub.

@Bill_Wang, thanks for becoming a member of the discussion board.

Have you ever examined the code with out the goroutine? That’s, let the code contained in the nameless func run immediately in foremost.

My guess is that cmd.Wait() continues earlier than the goroutine is ready to learn from stdout.


For different readers, that is the code in query:

package deal foremost

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

func foremost() {
	cmd := exec.Command("mtr", "-p", "-c", "10", "www.qq.com")
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println(err)
	}
	if err := cmd.Begin(); err != nil {
		fmt.Println(err)
	}
	go func() {
		scr := bufio.NewScanner(stdout)
		for {
			if scr.Scan() {
				fmt.Println(scr.Textual content())
			}
			if scr.Err() != nil {
				return
			}
		}
	}()
	if err := cmd.Wait(); err != nil {
		fmt.Println(err)
	}
}

1 Like

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments