-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdline.go
61 lines (54 loc) · 1.24 KB
/
cmdline.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
package main
import (
"bytes"
"errors"
"fmt"
"os"
"strings"
)
type CmdLine struct {
pid int
cmdline string
err error
}
func readCmdLine(pid int) (string, error) {
path := fmt.Sprintf("/proc/%d/cmdline", pid)
contents, err := os.ReadFile(path)
if err == nil {
s := string(bytes.Trim(contents, "\x00"))
replacer := strings.NewReplacer("\x00", " ")
s = replacer.Replace(s)
if len(s) == 0 {
return "", errors.New(fmt.Sprintf("Read zero size string from %s: %s", path, s))
} else {
return s, nil
}
} else {
return "", err
}
}
func cmdLineReader(pid int, output chan CmdLine) {
cmdline, err := readCmdLine(pid)
output <- CmdLine{pid, cmdline, err}
}
func reduceCmdLines(cmdLineChannelMap map[int](chan CmdLine)) map[int]string {
pidCmdLineMap := map[int]string{}
for _, ch := range cmdLineChannelMap {
for cmdline := range ch {
if cmdline.err == nil {
pidCmdLineMap[cmdline.pid] = cmdline.cmdline
}
close(ch)
}
}
return pidCmdLineMap
}
func dispatchCmdLineReaders(pids []int) map[int](chan CmdLine) {
cmdLineChannelMap := map[int](chan CmdLine){}
for _, pid := range pids {
chCmdLine := make(chan CmdLine, 1)
cmdLineChannelMap[pid] = chCmdLine
go cmdLineReader(pid, chCmdLine)
}
return cmdLineChannelMap
}