Skip to content

Commit 2210a0e

Browse files
committed
fix(command): fix rare race condition on log line stream at command completion
1 parent f8a677a commit 2210a0e

1 file changed

Lines changed: 9 additions & 18 deletions

File tree

internal/command/start.go

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ func (c *Cmder) Start(cmd *exec.Cmd) (
2121
func start(cmd execCmd) (stdoutLines, stderrLines <-chan string,
2222
waitError <-chan error, startErr error,
2323
) {
24-
stop := make(chan struct{})
2524
stdoutReady := make(chan struct{})
2625
stdoutLinesCh := make(chan string)
2726
stdoutDone := make(chan struct{})
@@ -33,22 +32,20 @@ func start(cmd execCmd) (stdoutLines, stderrLines <-chan string,
3332
if err != nil {
3433
return nil, nil, nil, err
3534
}
36-
go streamToChannel(stdoutReady, stop, stdoutDone, stdout, stdoutLinesCh)
35+
go streamToChannel(stdoutReady, stdoutDone, stdout, stdoutLinesCh)
3736

3837
stderr, err := cmd.StderrPipe()
3938
if err != nil {
4039
_ = stdout.Close()
41-
close(stop)
4240
<-stdoutDone
4341
return nil, nil, nil, err
4442
}
45-
go streamToChannel(stderrReady, stop, stderrDone, stderr, stderrLinesCh)
43+
go streamToChannel(stderrReady, stderrDone, stderr, stderrLinesCh)
4644

4745
err = cmd.Start()
4846
if err != nil {
4947
_ = stdout.Close()
5048
_ = stderr.Close()
51-
close(stop)
5249
<-stdoutDone
5350
<-stderrDone
5451
return nil, nil, nil, err
@@ -57,19 +54,20 @@ func start(cmd execCmd) (stdoutLines, stderrLines <-chan string,
5754
waitErrorCh := make(chan error)
5855
go func() {
5956
err := cmd.Wait()
60-
_ = stdout.Close()
61-
_ = stderr.Close()
62-
close(stop)
6357
<-stdoutDone
6458
<-stderrDone
59+
_ = stdout.Close()
60+
_ = stderr.Close()
6561
waitErrorCh <- err
6662
}()
6763

64+
<-stdoutReady
65+
<-stderrReady
66+
6867
return stdoutLinesCh, stderrLinesCh, waitErrorCh, nil
6968
}
7069

71-
func streamToChannel(ready chan<- struct{},
72-
stop <-chan struct{}, done chan<- struct{},
70+
func streamToChannel(ready chan<- struct{}, done chan<- struct{},
7371
stream io.Reader, lines chan<- string,
7472
) {
7573
defer close(done)
@@ -89,12 +87,5 @@ func streamToChannel(ready chan<- struct{},
8987
if err == nil || errors.Is(err, os.ErrClosed) {
9088
return
9189
}
92-
93-
// ignore the error if it is stopped.
94-
select {
95-
case <-stop:
96-
return
97-
default:
98-
lines <- "stream error: " + err.Error()
99-
}
90+
lines <- "stream error: " + err.Error()
10091
}

0 commit comments

Comments
 (0)