英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论