Files
4566704 30a0889ffa feat(monitor): 自 go-hua 迁入系统资源监控
- Start 后台每秒采集(CPU/内存/磁盘/网络/进程/连接/主机), GetInfo 取快照
- 基于 gopsutil, 附测试、examples/monitor 例程与包 README
2026-09-20 12:29:37 +08:00

81 lines
1.7 KiB
Go

package monitor
import (
"github.com/shirou/gopsutil/v3/process"
"path/filepath"
)
// MemoryInfoStat 进程内存信息(RSS/虚拟内存)
type MemoryInfoStat struct {
Rss uint64 `json:"res"`
Vms uint64 `json:"vms"`
}
// ProcessInfo 进程信息(PID/路径/CPU/内存占用与启动时间)
type ProcessInfo struct {
Pid int32 `json:"pid"`
Name string `json:"name"`
ExE string `json:"exe"`
Cmd string `json:"cmd"`
Cpu float64 `json:"cpu"`
Mem MemoryInfoStat `json:"mem"`
CreateTime int64 `json:"createTime"`
}
// GetProcessInfo 获取所有进程信息
func GetProcessInfo() ([]ProcessInfo, error) {
v, err := process.Processes()
if err != nil {
return nil, err
}
info := make([]ProcessInfo, len(v))
for i, p := range v {
name := ""
exe, _ := p.Exe()
cmd, _ := p.Cmdline()
// 先从执行文件中获取进程名
// 如果执行文件为空,再调用 Name() 方式,Name()方式很占用CPU
if exe == "" {
name, _ = p.Name()
} else {
name = filepath.Base(exe)
}
mem, _ := p.MemoryInfo()
cpu, _ := p.CPUPercent()
createTime, _ := p.CreateTime()
p.Times()
// 不获取线程数 太占用用CPU
// p.NumThreads()
info[i].Pid = p.Pid
info[i].Name = name
info[i].ExE = exe
info[i].Cmd = cmd
info[i].Cpu = cpu
if mem != nil {
info[i].Mem = MemoryInfoStat{
Rss: mem.RSS,
Vms: mem.VMS,
}
}
info[i].CreateTime = createTime
if name == "QQ.exe" {
//fmt.Printf("Pid:%d name:%s exe:%s\n", p.Pid, name, exe)
//fmt.Printf("工作集:%d 提交大小:%d\n", mem.RSS, mem.VMS)
//fmt.Printf("CPU:%.2f%% \n", cpu)
}
}
if err != nil {
return nil, err
}
return info, nil
}