Skip to content

Commit 92f4c03

Browse files
synchronize writes while running cmd to avoid data race (#624)
Co-authored-by: anishnaik <[email protected]>
1 parent 402d4e1 commit 92f4c03

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

utils/process_utils.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"io"
66
"os/exec"
77
"runtime"
8+
"sync"
89
)
910

1011
// RunCommandWithOutputAndError runs a given exec.Cmd and returns the stdout, stderr, and
@@ -13,9 +14,12 @@ func RunCommandWithOutputAndError(command *exec.Cmd) ([]byte, []byte, []byte, er
1314
// Create our buffers to capture output and errors.
1415
var bStdout, bStderr, bCombined bytes.Buffer
1516

17+
// Create a synchronized writer over bCombined to avoid data race.
18+
var combinedWriter io.Writer = &synchronizedWriter{writer: &bCombined}
19+
1620
// Create multi writers to capture output into individual and combined buffers
17-
stdoutMulti := io.MultiWriter(&bStdout, &bCombined)
18-
stderrMulti := io.MultiWriter(&bStderr, &bCombined)
21+
stdoutMulti := io.MultiWriter(&bStdout, combinedWriter)
22+
stderrMulti := io.MultiWriter(&bStderr, combinedWriter)
1923

2024
// Set our writers
2125
command.Stdout = stdoutMulti
@@ -42,3 +46,15 @@ func IsMacOSEnvironment() bool {
4246
func IsLinuxEnvironment() bool {
4347
return runtime.GOOS == "linux"
4448
}
49+
50+
// synchronizedWriter wraps an io.Writer to avoid a data race when writing.
51+
type synchronizedWriter struct {
52+
writer io.Writer
53+
mutex sync.Mutex
54+
}
55+
56+
func (s *synchronizedWriter) Write(p []byte) (n int, err error) {
57+
s.mutex.Lock()
58+
defer s.mutex.Unlock()
59+
return s.writer.Write(p)
60+
}

0 commit comments

Comments
 (0)