英文:
Why doesn't os/exec.CombinedOutput() have a race condition?
问题
Go的bytes.Buffer
不是线程安全的。然而,当我阅读源代码时,我注意到os/exec.CombinedOutput()
在c.Stdout
和c.Stderr
上使用了同一个缓冲区。进一步阅读该包的实现,我发现在写入c.Stderr
/c.Stdout
时没有同步操作。
我是否漏掉了什么,或者我发现了一个可能的同步问题?据我所知,子进程可以同时写入stderr和stdout。
英文:
The Go bytes.Buffer
isn't thread-safe. Yet, when I read the source code I notice that os/exec.CombinedOutput()
uses the same buffer for both c.Stdout
and c.Stderr
. Further reading the implementation of the package it looks like there is no synchronisation when writing to the c.Stderr
/c.Stdout
here.
Am I missing something or have I found a possible synchronisation issue? AFAIK stderr and stdout can be written to concurrently by the child process.
答案1
得分: 3
Stderr和Stdout如果作为相同的写入器,根据Cmd文档的说明,它们不会同时被写入:
> 如果Stdout和Stderr是相同的写入器,最多只有一个goroutine会调用Write。
这个特性在Cmd.stderr函数中实现。如果Stdout和Stderr是相同的,那么相同的文件描述符(fd)会传递给子进程的stdout和stderr。在文件描述符是一个带有用于传输的goroutine的管道的情况下,只有一个goroutine会写入到Stdout/Stderr。
英文:
Stderr and Stdout are not written concurrently if they are the same writer as stated in the Cmd documentation:
> If Stdout and Stderr are the same writer, at most one goroutine at a time will call Write.
This feature is implemented in the Cmd.stderr function. If Stdout and Stderr are the same, then the same fd is passed the child process stdout and stderr. In the case where the fd is a pipe with a goroutine to pump it, there's only one goroutine writing to Stdout/Stderr.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论