From 1a459f8317caf012f0138198a1e1b037bfa56ac8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Greg=C3=B3rio=20G=2E?= Date: Fri, 20 Sep 2024 17:21:18 -0300 Subject: [PATCH] fix(tests): possible goroutine leak (#4306) Fix a possible goroutine leak in ExecCmdBgWithSudoAndCtx(). --- tests/testutils/exec.go | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tests/testutils/exec.go b/tests/testutils/exec.go index 16a9eb099dc0..80a8cae6410e 100644 --- a/tests/testutils/exec.go +++ b/tests/testutils/exec.go @@ -162,22 +162,28 @@ func ExecCmdBgWithSudoAndCtx(ctx context.Context, command string) (int, chan err // Kill the command if the context is canceled (and signal that it was killed). go func(pid *atomic.Int64) { - <-ctx.Done() - p := pid.Load() - if p > 0 { - // discover all child processes - childPIDs, err := DiscoverChildProcesses(int(p)) - if err != nil { - cmdStatus <- &failedToKillProcess{command: command, err: err} - } - // kill all child processes (sudo creates childs in new process group) - for _, childPID := range childPIDs { - err := SudoKillProcess(childPID, false) + select { + case <-ctx.Done(): + p := pid.Load() + if p > 0 { + // discover all child processes + childPIDs, err := DiscoverChildProcesses(int(p)) if err != nil { cmdStatus <- &failedToKillProcess{command: command, err: err} } + // kill all child processes (sudo creates childs in new process group) + for _, childPID := range childPIDs { + err := SudoKillProcess(childPID, false) + if err != nil { + cmdStatus <- &failedToKillProcess{command: command, err: err} + } + } } + + case <-cmdStatus: + // command finished before the context was canceled } + commandEndWG.Wait() close(cmdStatus) // signal command exited }(&pid)