-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproc_linux.go
66 lines (52 loc) · 1.33 KB
/
proc_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
// +build linux
package proc
import (
"bytes"
"io/ioutil"
"regexp"
"strconv"
"strings"
)
func ps(pid int) []*ProcessInfo {
processes := []*ProcessInfo{}
files, _ := ioutil.ReadDir("/proc")
for _, file := range files {
procPid, err := strconv.Atoi(file.Name())
// Ignore non-numeric entries
if err != nil {
continue
}
// Ignore a non-matching pid
if pid >= 0 && procPid != pid {
continue
}
process := ProcessInfo{Pid: procPid, CommandLine: []string{}}
if commandLine, err := ioutil.ReadFile("/proc/" + file.Name() + "/cmdline"); err != nil {
continue // Process terminated
} else {
args := bytes.Split(commandLine, []byte{'\x00'})
for _, arg := range args {
strArg := strings.TrimSpace(string(arg))
if len(strArg) == 0 {
continue
}
process.CommandLine = append(process.CommandLine, strArg)
}
}
if stat, err := ioutil.ReadFile("/proc/" + file.Name() + "/stat"); err != nil {
continue // Process terminated
} else {
statRegex := regexp.MustCompile("\\(([^\\)]+)\\)")
parts := statRegex.FindStringSubmatch(string(stat))
if len(parts) == 2 {
process.Command = strings.TrimSpace(parts[1])
}
}
processes = append(processes, &process)
// Break if this is the one process we were looking for
if process.Pid == pid {
break
}
}
return processes
}