Skip to content

Commit

Permalink
fix(tests): possible goroutine leak (aquasecurity#4306)
Browse files Browse the repository at this point in the history
Fix a possible goroutine leak in ExecCmdBgWithSudoAndCtx().
  • Loading branch information
geyslan authored Sep 20, 2024
1 parent 9d62cbd commit 1a459f8
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions tests/testutils/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 1a459f8

Please sign in to comment.