Skip to content

Commit 12020ac

Browse files
committed
Added WaitWithinContext method.
1 parent 6444974 commit 12020ac

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

process.go

+16-10
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,21 @@ func (p *Process) Wait() error {
138138
return p.cmd.Wait()
139139
}
140140

141+
// WaitWithinContext wait for the process to complete. If the given context is canceled
142+
// before the normal process termination, the process is killed.
143+
func (p *Process) WaitWithinContext(ctx context.Context) error {
144+
completed := make(chan struct{})
145+
defer close(completed)
146+
go func() {
147+
select {
148+
case <-ctx.Done():
149+
p.Kill()
150+
case <-completed:
151+
}
152+
}()
153+
return p.Wait()
154+
}
155+
141156
// Signal sends a signal to the Process. Sending Interrupt on Windows is not implemented.
142157
func (p *Process) Signal(sig os.Signal) error {
143158
return p.cmd.Process.Signal(sig)
@@ -188,16 +203,7 @@ func (p *Process) RunWithinContext(ctx context.Context) error {
188203
if err := p.Start(); err != nil {
189204
return err
190205
}
191-
completed := make(chan struct{})
192-
defer close(completed)
193-
go func() {
194-
select {
195-
case <-ctx.Done():
196-
p.Kill()
197-
case <-completed:
198-
}
199-
}()
200-
return p.Wait()
206+
return p.WaitWithinContext(ctx)
201207
}
202208

203209
// RunAndCaptureOutput starts the specified command and waits for it to complete. If the given context

0 commit comments

Comments
 (0)