我已将以下内容添加到 stdout 和 stderr goroutine (go func() …) 以等待获取output并error完成。现在我希望外部函数将等待两个例程完成。
func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanout.Split(bufio.ScanRunes)
go func() {
for scanout.Scan() {
fmt.Print(scanout.Text())
}
}()
go func() {
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
}()
}
现在我尝试添加等待组,但它不起作用,因为我不确定如何传递等待组实例,知道吗?
func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanout.Split(bufio.ScanRunes)
var waitgroup sync.WaitGroup
waitgroup.Add(1)
go func() {
for scanout.Scan() {
fmt.Print(scanout.Text())
}
}()
waitgroup.Wait()
waitgroup.Add(1)
go func() {
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
}()
waitgroup.Wait()
}
更新
应该是这样吗?
func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanout.Split(bufio.ScanRunes)
var waitgroup sync.WaitGroup
waitgroup.Add(2)
go func() {
for scanout.Scan() {
fmt.Print(scanout.Text())
}
}()
go func() {
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
}()
waitgroup.Wait()
}
慕森卡
相关分类