为什么os/exec.CombinedOutput()没有竞态条件?

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

Why doesn't os/exec.CombinedOutput() have a race condition?

问题

Go的bytes.Buffer不是线程安全的。然而,当我阅读源代码时,我注意到os/exec.CombinedOutput()c.Stdoutc.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.

huangapple
  • 本文由 发表于 2017年3月31日 18:36:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/43138596.html
匿名

发表评论

匿名网友

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

确定