From 7f2d3f2c5c783dfacc7bc3bb86da4008d8b61bd6 Mon Sep 17 00:00:00 2001 From: Anton Averchenkov <84287187+averche@users.noreply.github.com> Date: Tue, 30 May 2023 12:23:51 -0400 Subject: [PATCH] fix exitCh race condition (#20817) --- command/agent/exec/exec.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/command/agent/exec/exec.go b/command/agent/exec/exec.go index fa91003964..a1ea97addc 100644 --- a/command/agent/exec/exec.go +++ b/command/agent/exec/exec.go @@ -257,7 +257,16 @@ func (s *Server) bounceCmd(newEnvVars []string) error { } s.childProcess = proc - // listen if the child process exits and bubble it up to the main loop + if err := s.childProcess.Start(); err != nil { + return fmt.Errorf("error starting the child process: %w", err) + } + + s.childProcessState = childProcessStateRunning + + // Listen if the child process exits and bubble it up to the main loop. + // + // NOTE: this must be invoked after child.Start() to avoid a potential + // race condition with ExitCh not being initialized. go func() { ctx, cancel := context.WithCancel(context.Background()) s.childProcessExitCodeCloser = cancel @@ -270,10 +279,5 @@ func (s *Server) bounceCmd(newEnvVars []string) error { } }() - if err := s.childProcess.Start(); err != nil { - return fmt.Errorf("error starting child process: %w", err) - } - s.childProcessState = childProcessStateRunning - return nil }