![](/img/trans.png)
[英]Bufio scan function is waiting for sometime for the last buffer (tailed operation) in GO
[英]Go scan buffer hangs sometimes
我使用以下代碼可以正常工作,但是在某些情況下,進程卡住了,我沒有看到任何 output。 示例此代碼運行npm install
或mvn clean install
並且大部分時間它運行良好但有時它掛起並且您沒有得到任何 output
func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanerr := bufio.NewScanner(stderr)
scanout.Split(bufio.ScanRunes)
for scanout.Scan() {
fmt.Print(scanout.Text())
}
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
return scanout, scanerr
}
現在,如果我像以下那樣更改順序(首先出錯,然后是 stdout),當命令掛起時,我會收到一些錯誤 output 但是我看不到 output 在線,當你運行命令時,你會看到一些 Z78E6221F3983D11CEDZF 和完成時你看到所有rest。 您可以等待 output 2 分鍾或更長時間,然后在過程結束時立即獲得長 output。
如何解決我將能夠在線獲取 output 並在進程掛起時獲得一些反饋的問題?
func exec(stdout io.Reader, stderr io.Reader) (*bufio.Scanner, *bufio.Scanner) {
scanout := bufio.NewScanner(stdout)
scanerr := bufio.NewScanner(stderr)
scanout.Split(bufio.ScanRunes)
for scanout.Scan() {
fmt.Print(scanout.Text())
}
scanerr.Split(bufio.ScanRunes)
for scanerr.Scan() {
fmt.Print(scanerr.Text())
}
}
return scanout, scanerr
}
更新
應該是這樣嗎?
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())
}
}()
}
在第一種情況下,您正在從進程的標准輸出中讀取,直到進程結束。 然后你從標准錯誤中讀取。 在第二種情況下,您首先從 err 讀取,然后再讀取。 你應該讀他們兩個。 要么使用 Cmd.CombinedOutput 來返回它們,要么啟動兩個 goroutine,一個從 stdin 讀取,一個從 stderr 讀取,直到流關閉。
scanout := bufio.NewScanner(stdout)
scanout.Split(bufio.ScanRunes)
go func() {
for scanout.Scan() {
fmt.Print(scanout.Text())
}
}()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.