-
Notifications
You must be signed in to change notification settings - Fork 0
/
proc_linux.go
58 lines (48 loc) · 1001 Bytes
/
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
package proc
import (
"fmt"
"os"
"path/filepath"
"strconv"
)
// listProcs returns a list of the running processes.
func listProcs() ([]*Proc, error) {
var (
comm string
state byte
ppid int
)
procfs, err := os.Open("/proc")
if err != nil {
return nil, err
}
defer procfs.Close()
names, err := procfs.Readdirnames(0)
if err != nil {
return nil, err
}
var procs []*Proc
for _, name := range names {
// Skip non pid paths.
pid, err := strconv.Atoi(name)
if err != nil {
continue
}
stat, err := os.Open(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
if err != nil {
// If it can't be opened the process has exited.
if os.IsNotExist(err) {
continue
}
return nil, err
}
defer stat.Close()
// Store the stat info needed to retreive the ppid.
_, err = fmt.Fscanf(stat, "%d %s %c %d", &pid, &comm, &state, &ppid)
if err != nil {
return nil, err
}
procs = append(procs, &Proc{Pid: pid, Ppid: ppid})
}
return procs, nil
}