-
Notifications
You must be signed in to change notification settings - Fork 83
/
proc.go
105 lines (83 loc) · 1.73 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package nux
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"strconv"
"strings"
"github.com/toolkits/file"
)
type Proc struct {
Pid int
Name string
Cmdline string
}
func (this *Proc) String() string {
return fmt.Sprintf("<Pid:%d, Name:%s, Cmdline:%s>", this.Pid, this.Name, this.Cmdline)
}
func AllProcs() (ps []*Proc, err error) {
var dirs []string
dirs, err = file.DirsUnder(Root() + "/proc")
if err != nil {
return
}
size := len(dirs)
if size == 0 {
return
}
for i := 0; i < size; i++ {
pid, e := strconv.Atoi(dirs[i])
if e != nil {
continue
}
statusFile := fmt.Sprintf(Root()+"/proc/%d/status", pid)
cmdlineFile := fmt.Sprintf(Root()+"/proc/%d/cmdline", pid)
if !file.IsExist(statusFile) || !file.IsExist(cmdlineFile) {
continue
}
name, e := ReadName(statusFile)
if e != nil {
continue
}
cmdlineBytes, e := file.ToBytes(cmdlineFile)
if e != nil {
continue
}
cmdlineBytesLen := len(cmdlineBytes)
if cmdlineBytesLen == 0 {
continue
}
noNut := make([]byte, 0, cmdlineBytesLen)
for j := 0; j < cmdlineBytesLen; j++ {
if cmdlineBytes[j] != 0 {
noNut = append(noNut, cmdlineBytes[j])
}
}
p := Proc{Pid: pid, Name: name, Cmdline: string(noNut)}
ps = append(ps, &p)
}
return
}
func ReadName(path string) (name string, err error) {
var content []byte
content, err = ioutil.ReadFile(path)
if err != nil {
return
}
reader := bufio.NewReader(bytes.NewBuffer(content))
for {
var bs []byte
bs, err = file.ReadLine(reader)
if err == io.EOF {
return
}
line := string(bs)
colonIndex := strings.Index(line, ":")
if strings.TrimSpace(line[0:colonIndex]) == "Name" {
return strings.TrimSpace(line[colonIndex+1:]), nil
}
}
return
}