Skip to content

Commit 5824248

Browse files
committed
avoid goroutine leak
1 parent 47fa848 commit 5824248

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

timeout.go

+15-9
Original file line numberDiff line numberDiff line change
@@ -132,12 +132,21 @@ func (tio *Timeout) wait(ctx context.Context) *ExitStatus {
132132
ex := &ExitStatus{}
133133
cmd := tio.getCmd()
134134
exitChan := getExitChan(cmd)
135-
killCh := make(chan struct{})
136-
if tio.KillAfter > 0 {
137-
go func() {
138-
time.Sleep(tio.Duration + tio.KillAfter)
135+
killCh := make(chan struct{}, 2)
136+
done := make(chan struct{})
137+
defer close(done)
138+
139+
delayedKill := func(dur time.Duration) {
140+
select {
141+
case <-done:
142+
return
143+
case <-time.After(dur):
139144
killCh <- struct{}{}
140-
}()
145+
}
146+
}
147+
148+
if tio.KillAfter > 0 {
149+
go delayedKill(tio.Duration + tio.KillAfter)
141150
}
142151
for {
143152
select {
@@ -160,10 +169,7 @@ func (tio *Timeout) wait(ctx context.Context) *ExitStatus {
160169
// XXX handling etx.Err()?
161170
tio.terminate()
162171
ex.typ = exitTypeCanceled
163-
go func() {
164-
time.Sleep(tio.getKillAfterCancel())
165-
killCh <- struct{}{}
166-
}()
172+
go delayedKill(tio.getKillAfterCancel())
167173
}
168174
}
169175
}

0 commit comments

Comments
 (0)