pid.go 1.42 KB
Newer Older
liming6's avatar
liming6 committed
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
package utils

import (
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"

	"github.com/shirou/gopsutil/v4/process"
)

var (
	RePidNS = regexp.MustCompile(`pid:\[([1-9][0-9]*)]$`) // 匹配pid命名空间的正则表达式 pid:[4026545939]
)

// GetPidNS 获取指定进程的Pid命名空间号
func GetPidNS(pid uint64) (uint64, error) {
	str, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid))
	if err != nil {
		return 0, err
	}
	if !RePidNS.MatchString(str) {
		return 0, fmt.Errorf("error matching pid")
	}
	strs := RePidNS.FindStringSubmatch(str)
	if len(strs) < 2 {
		return 0, fmt.Errorf("error matching pid")
	}
	return strconv.ParseUint(strs[1], 10, 64)
}

// GetProcessInfo 获取进程信息
func GetProcessInfo(pid int32) {
	p, err := process.NewProcess(pid)
	if err != nil {
		return
	}
39
	p.Times()
liming6's avatar
liming6 committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
	cmdStr, err := p.Cmdline()
	if err != nil {
		return
	}
	log.Println(cmdStr)
}

func GetProcessByName(cmdline string) ([]*process.Process, error) {
	p, err := process.Processes()
	if err != nil {
		return nil, err
	}
	result := make([]*process.Process, 0)
	for _, i := range p {
		c, innerErr := i.CmdlineSlice()
		if innerErr != nil || len(c) <= 0 {
			continue
		}
		if c[0] == cmdline {
			result = append(result, i)
		}
	}
	return result, nil
}
64
65
66
67
68
69
70
71
72

// GetProcessCPUUsage 获取进程的CPU使用率
func GetProcessCPUUsage(pid int32) (float64, error) {
	p, err := process.NewProcess(pid)
	if err != nil {
		return 0, err
	}
	return p.CPUPercent()
}