-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec_unix.go
59 lines (52 loc) · 1.33 KB
/
exec_unix.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
47
48
49
50
51
52
53
54
55
56
57
58
59
//go:build !windows
// +build !windows
package exec
import (
"context"
"os"
"os/exec"
"syscall"
)
var defaultSignal = syscall.SIGTERM
// Reference code:
// https://github.com/Songmu/timeout/blob/9710262dc02f66fdd69a6cd4c8143204006d5843/timeout_unix.go
func command(name string, arg ...string) *exec.Cmd {
cmd := exec.Command(name, arg...) // #nosec
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.SysProcAttr.Setpgid = true // force setpgid
return cmd
}
func commandContext(ctx context.Context, name string, arg ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, name, arg...) // #nosec
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.SysProcAttr.Setpgid = true // force setpgid
return cmd
}
func terminate(cmd *exec.Cmd, sig os.Signal) error {
syssig, ok := sig.(syscall.Signal)
if !ok {
return cmd.Process.Signal(sig)
}
if cmd.Process == nil {
return nil
}
err := syscall.Kill(-cmd.Process.Pid, syssig)
if err != nil {
return cmd.Process.Signal(syssig) // fallback
}
if syssig != syscall.SIGKILL && syssig != syscall.SIGCONT {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGCONT)
}
return nil
}
func killall(cmd *exec.Cmd) error {
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
if err != nil {
return cmd.Process.Kill() // fallback
}
return nil
}