-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathgow_ps_linux.go
87 lines (72 loc) · 1.57 KB
/
gow_ps_linux.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//go:build linux
package main
import (
"os"
"path/filepath"
"strconv"
"strings"
"github.com/mitranim/gg"
)
func SubPids(topPid int, verb bool) ([]int, error) {
pid := os.Getpid()
pids, err := SubPidsViaProcDir(pid)
if err == nil {
return pids, nil
}
if verb {
log.Println(`unable to get pids from "/proc", falling back on "ps":`, err)
}
return SubPidsViaPs(pid)
}
func SubPidsViaProcDir(topPid int) ([]int, error) {
procEntries, err := os.ReadDir(`/proc`)
if err != nil {
return nil, gg.Wrap(err, `unable to read directory "/proc"`)
}
// Index of child pids by ppid.
ppidToPids := map[int][]int{}
for _, entry := range procEntries {
if !entry.IsDir() {
continue
}
pidStr := entry.Name()
pid, err := strconv.Atoi(pidStr)
if err != nil {
// Non-numeric names don't describe processes, skip.
continue
}
status, err := os.ReadFile(filepath.Join(`/proc`, pidStr, `status`))
if err != nil {
// Process may have terminated, skip.
continue
}
ppid := statusToPpid(gg.ToString(status))
if ppid != 0 {
ppidToPids[ppid] = append(ppidToPids[ppid], pid)
}
}
return procIndexToDescs(ppidToPids, topPid, 0), nil
}
func statusToPpid(src string) (_ int) {
const prefix0 = `PPid:`
const prefix1 = `Ppid:`
ind := strings.Index(src, prefix0)
if ind >= 0 {
ind += len(prefix0)
} else {
ind = strings.Index(src, prefix1)
if ind < 0 {
return
}
ind += len(prefix1)
}
src = src[ind:]
ind = strings.Index(src, "\n")
if ind < 0 {
return
}
src = src[:ind]
src = strings.TrimSpace(src)
out, _ := strconv.Atoi(src)
return out
}