-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathps_linux.go
65 lines (55 loc) · 1.18 KB
/
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
//go:build linux
package gotool
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
)
// PsByName 根据程序名查询进程列表
//
// name: 程序名
func PsByName(name string) ([]Process, error) {
processes := make([]Process, 0)
name = filepath.Base(name)
files, err := ioutil.ReadDir("/proc")
if err != nil {
return nil, err
}
for _, file := range files {
if !file.IsDir() {
continue
}
pid := file.Name()
// Read the process command
cmdPath := filepath.Join("/proc", file.Name(), "cmdline")
cmdBytes, err := ioutil.ReadFile(cmdPath)
if err != nil {
continue
}
cmd := string(cmdBytes)
if strings.Contains(cmd, name) {
ppid, err := getParentPid(pid)
if err == nil {
processes = append(processes, Process{
Pid: file.Name(),
PPid: ppid,
Cmd: cmd,
})
}
}
}
return processes, nil
}
func getParentPid(pid string) (string, error) {
statPath := filepath.Join("/proc", pid, "stat")
statBytes, err := ioutil.ReadFile(statPath)
if err != nil {
return "", err
}
fields := strings.Fields(string(statBytes))
if len(fields) < 4 {
return "", fmt.Errorf("invalid stat file for pid %s", pid)
}
return fields[3], nil
}