/
process.go
70 lines (64 loc) · 1.59 KB
/
process.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
60
61
62
63
64
65
66
67
68
69
70
package util
import (
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/shirou/gopsutil/process"
"github.com/jenkins-x/jx/pkg/log"
)
func RunCommandBackground(name string, output io.Writer, verbose bool, args ...string) error {
e := exec.Command(name, args...)
e.Stdout = output
e.Stderr = output
os.Setenv("PATH", PathWithBinary())
err := e.Start()
if err != nil && verbose {
log.Errorf("Error: Command failed to start %s %s\n", name, strings.Join(args, " "))
}
return err
}
func KillProcesses(binary string) error {
processes, err := process.Processes()
if err != nil {
return err
}
m := map[int32]bool{}
_, err = KillProcessesTree(binary, processes, m)
return err
}
func KillProcessesTree(binary string, processes []*process.Process, m map[int32]bool) (bool, error) {
var answer error
done := false
for _, p := range processes {
pid := p.Pid
if pid > 0 && !m[pid] {
m[pid] = true
exe, err := p.Name()
if err == nil && exe != "" {
_, name := filepath.Split(exe)
// if windows lets remove .exe
name = strings.TrimSuffix(name, ".exe")
if name == binary {
log.Infof("killing %s process with pid %d\n", binary, int(pid))
err = p.Terminate()
if err != nil {
log.Warnf("Failed to terminate process with pid %d: %s", int(pid), err)
} else {
log.Infof("killed %s process with pid %d\n", binary, int(pid))
}
return true, err
}
}
children, err := p.Children()
if err == nil {
done, err = KillProcessesTree(binary, children, m)
if done {
return done, err
}
}
}
}
return done, answer
}