Merge pull request #18412 from aaronlehmann/runcommand-race

Fix race in RunCommandWithOutputForDuration
This commit is contained in:
Alexander Morozov 2015-12-03 19:35:04 -08:00
commit 7c1c96551d
1 changed files with 14 additions and 8 deletions

View File

@ -104,19 +104,25 @@ func RunCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (out
} }
cmd.Stderr = &outputBuffer cmd.Stderr = &outputBuffer
done := make(chan error)
// Start the command in the main thread.. // Start the command in the main thread..
err = cmd.Start() err = cmd.Start()
if err != nil { if err != nil {
err = fmt.Errorf("Fail to start command %v : %v", cmd, err) err = fmt.Errorf("Fail to start command %v : %v", cmd, err)
} }
type exitInfo struct {
exitErr error
exitCode int
}
done := make(chan exitInfo, 1)
go func() { go func() {
// And wait for it to exit in the goroutine :) // And wait for it to exit in the goroutine :)
exitErr := cmd.Wait() info := exitInfo{}
exitCode = ProcessExitCode(exitErr) info.exitErr = cmd.Wait()
done <- exitErr info.exitCode = ProcessExitCode(info.exitErr)
done <- info
}() }()
select { select {
@ -126,9 +132,9 @@ func RunCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (out
fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr) fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr)
} }
timedOut = true timedOut = true
break case info := <-done:
case err = <-done: err = info.exitErr
break exitCode = info.exitCode
} }
output = outputBuffer.String() output = outputBuffer.String()
return return