Is there a race in exec.CombinedOutput?

136 views
Skip to first unread message

王富民awaw

unread,
Oct 4, 2023, 1:55:16 AM10/4/23
to golang-nuts
exec.CombinedOutput uses the same io.Writer for both stdout and stderr in  exec.go - Go (opensource.google) .
This io.Writer is written in  exec.go - Go (opensource.google) .
These two writes happens concurrently in two goroutines in exec.go - Go (opensource.google) .
As far as I know, bytes.Buffer is not safe to concurrent writes.
Is this not a race?

Jason Phillips

unread,
Oct 4, 2023, 4:58:29 AM10/4/23
to golang-nuts
From the Stdout/Stderr field documentation on the os/exec.Cmd type:

"If Stdout and Stderr are the same writer, and have a type that can be compared with ==, at most one goroutine at a time will call Write."

Brian Candler

unread,
Oct 4, 2023, 12:36:10 PM10/4/23
to golang-nuts
Code reference:

* c.writerDescriptor creates the pipe, and a copying function is appended to the slice c.goroutine. This slice contains the functions which will be started in their own goroutines.
* c.childStdout calls c.writerDescriptor
* c.childStderr reuses the exiting childStdout if Stdout and Stderr are the same (and therefore there is still only one function in c.goroutine)
* interfaceEqual implements the check that Jason quoted:

王富民awaw

unread,
Oct 5, 2023, 1:12:01 AM10/5/23
to golang-nuts
That's interesting!
Thanks Jason and Brian for educating me! Thanks!

Reply all
Reply to author
Forward
0 new messages