Skip to content

Commit

Permalink
Use chan only to notify command is done to avoid race condition
Browse files Browse the repository at this point in the history
Signed-off-by: Shinnosuke Sawada-Dazai <[email protected]>
  • Loading branch information
Warashi committed Sep 30, 2024
1 parent c1a06aa commit 6e7b336
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions pkg/app/launcher/cmd/launcher/binary.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"os"
"os/exec"
"path/filepath"
"sync/atomic"
"syscall"
"time"

Expand All @@ -29,7 +30,8 @@ import (

type command struct {
cmd *exec.Cmd
stoppedCh chan error
stoppedCh chan struct{}
result atomic.Pointer[error]
}

func (c *command) IsRunning() bool {
Expand All @@ -50,9 +52,16 @@ func (c *command) GracefulStop(period time.Duration) error {
select {
case <-timer.C:
c.cmd.Process.Kill()
return <-c.stoppedCh
case err := <-c.stoppedCh:
return err
<-c.stoppedCh
if perr := c.result.Load(); perr != nil {
return *perr
}
return nil

Check warning on line 59 in pkg/app/launcher/cmd/launcher/binary.go

View check run for this annotation

Codecov / codecov/patch

pkg/app/launcher/cmd/launcher/binary.go#L59

Added line #L59 was not covered by tests
case <-c.stoppedCh:
if perr := c.result.Load(); perr != nil {
return *perr
}
return nil

Check warning on line 64 in pkg/app/launcher/cmd/launcher/binary.go

View check run for this annotation

Codecov / codecov/patch

pkg/app/launcher/cmd/launcher/binary.go#L64

Added line #L64 was not covered by tests
}
}

Expand All @@ -68,11 +77,12 @@ func runBinary(execPath string, args []string) (*command, error) {

c := &command{
cmd: cmd,
stoppedCh: make(chan error, 1),
stoppedCh: make(chan struct{}),
result: atomic.Pointer[error]{},
}
go func() {
err := cmd.Wait()
c.stoppedCh <- err
c.result.Store(&err)
close(c.stoppedCh)
}()

Expand Down

0 comments on commit 6e7b336

Please sign in to comment.