-
Notifications
You must be signed in to change notification settings - Fork 0
/
proc.go
73 lines (61 loc) · 1.17 KB
/
proc.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
71
72
73
package proc
import (
"os"
)
// Proc describes a process and its children.
type Proc struct {
Pid int `json:"pid"`
Ppid int `json:"ppid"`
Children []*Proc `json:"children"`
}
// Kill kills a process and its children.
func (proc *Proc) Kill() error {
p, err := os.FindProcess(proc.Pid)
if err != nil {
return err
}
err = p.Kill()
if err != nil {
return err
}
if proc.Children != nil {
for _, p := range proc.Children {
err = p.Kill()
if err != nil {
return err
}
}
}
return nil
}
// GetPidTree gets the process tree for a pid. The returned process structure
// is nil if the given pid is not a running process.
func GetPidTree(cpid int) (*Proc, error) {
var root *Proc
procs, err := listProcs()
if err != nil {
return nil, err
}
var children []*Proc
for _, proc := range procs {
// We've found the root process.
if proc.Pid == cpid {
root = proc
continue
}
// Found a child process.
if proc.Ppid == cpid {
p, err := GetPidTree(proc.Pid)
if err != nil {
return nil, err
}
if p != nil {
children = append(children, p)
}
}
}
if root != nil {
root.Children = children
}
return root, nil
}