forked from weaveworks/scope
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree.go
62 lines (52 loc) · 1.18 KB
/
tree.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
package process
import (
"fmt"
)
// Tree represents all processes on the machine.
type Tree interface {
GetParent(pid int) (int, error)
GetChildren(pid int) ([]int, error)
}
type tree struct {
processes map[int]Process
}
// NewTree returns a new Tree that can be polled.
func NewTree(walker Walker) (Tree, error) {
pt := tree{processes: map[int]Process{}}
err := walker.Walk(func(p, _ Process) {
pt.processes[p.PID] = p
})
return &pt, err
}
// GetParent returns the pid of the parent process for a given pid
func (pt *tree) GetParent(pid int) (int, error) {
proc, ok := pt.processes[pid]
if !ok {
return -1, fmt.Errorf("PID %d not found", pid)
}
return proc.PPID, nil
}
// GetChildren
func (pt *tree) GetChildren(pid int) ([]int, error) {
_, ok := pt.processes[pid]
if !ok {
return []int{}, fmt.Errorf("PID %d not found", pid)
}
var isChild func(id int) bool
isChild = func(id int) bool {
p, ok := pt.processes[id]
if !ok || p.PPID == 0 {
return false
} else if p.PPID == pid {
return true
}
return isChild(p.PPID)
}
children := []int{pid}
for id := range pt.processes {
if isChild(id) {
children = append(children, id)
}
}
return children, nil
}