-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrun.go
46 lines (40 loc) · 772 Bytes
/
run.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main
import (
"context"
"fmt"
"os/exec"
"syscall"
"time"
)
func runWithGracefulShutdown(ctx context.Context, cmd *exec.Cmd) error {
err := cmd.Start()
if err != nil {
return err
}
errc := make(chan error)
go func() {
select {
case errc <- nil:
return
case <-ctx.Done():
}
syscall.Kill(cmd.Process.Pid, syscall.SIGINT)
timer := time.NewTimer(30 * time.Second)
defer timer.Stop()
select {
case errc <- ctx.Err():
return
case <-timer.C:
syscall.Kill(cmd.Process.Pid, syscall.SIGKILL)
}
errc <- ctx.Err()
}()
waitErr := cmd.Wait()
if interruptErr := <-errc; interruptErr != nil {
return interruptErr
}
if waitErr != nil {
return fmt.Errorf("run command: %w with args %v", waitErr, cmd.Args)
}
return nil
}