Read result of command in Go

huangapple go评论78阅读模式
英文:

Read result of command in Go

问题

请看 https://play.golang.org/p/ljovw4QPSl
这个函数在本地执行一个命令,并返回标准输出和标准错误输出。它大部分时间都能正常工作,但有时候在第55行的stdoutbuf.ReadFrom()调用返回read |0: bad file descriptor。我无法弄清楚代码有什么问题。

英文:

See https://play.golang.org/p/ljovw4QPSl.
This function executes a command locally and returns both the stdout and stderr. It works most of the time, but sometimes the stdoutbuf.ReadFrom() call on line 55 returns read |0: bad file descriptor. I can't figure out what's wrong with the code.

答案1

得分: 1

你的goroutine在命令程序退出并被收集之前没有任何保证执行。如果你在每个goroutine的开头添加一个比命令的生命周期更长的睡眠时间,你会每次都看到这个错误。

在调用命令的Wait之前,先等待goroutine完成。这样可以确保进程仍然存在,供goroutine读取。

英文:

There's nothing guaranteeing your goruoutines are executed before your command program has exited and been collected. If you added a sleep at the start of each goroutine for longer than the life of the command, you would see this error every time.

Wait on the goroutines first, before calling Wait on the command. This will make sure the process is still around for your goroutines to read from.

huangapple
  • 本文由 发表于 2017年1月13日 02:03:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/41620019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定