process

  • 1 定义要采集的进程信息

//所要采集的进程信息
type Process struct {
	Pid     int32  `json:"Pid"`
	Name    string `json:"Name"`
	Cmdline string `json:"Cmdline"`
	Cwd     string `json:"Cwd"`
	Exe     string `json:"Exe"`
	ProcHash   string `json:"ProcHash"`  
}
  • 2 编写采集过程

import process
//调用Processes方法
procs, _ := process.Processes()
var procInfo []common.Process
for i := 0; i <= len(procs)-1; i++ {
    var proc common.Process
    proc.Name, _ = procs[i].Name()
    proc.Pid = procs[i].Pid
    proc.Cmdline, _ = procs[i].Cmdline()
    proc.Cwd, _ = procs[i].Cwd()
    proc.Exe, _ = procs[i].Exe()
    procInfo = append(procInfo, proc)
}
  • 3 Processes分析

进程相关信息的包来自 github.com/shirou/gopsutil/v3
3.1 Process

type Process struct {
	Pid            int32 `json:"pid"`
	name           string
	status         string
	parent         int32
	parentMutex    *sync.RWMutex // for windows ppid cache
	numCtxSwitches *NumCtxSwitchesStat
	uids           []int32
	gids           []int32
	groups         []int32
	numThreads     int32
	memInfo        *MemoryInfoStat
	sigInfo        *SignalInfoStat
	createTime     int64

	lastCPUTimes *cpu.TimesStat
	lastCPUTime  time.Time

	tgid int32
}

3.2 Processes

// Processes returns a slice of pointers to Process structs for all
// currently running processes.
func Processes() ([]*Process, error) {
	return ProcessesWithContext(context.Background())
}

func ProcessesWithContext(ctx context.Context) ([]*Process, error) {
	out := []*Process{}

	pids, err := PidsWithContext(ctx)
	if err != nil {
		return out, err
	}

	for _, pid := range pids {
		p, err := NewProcessWithContext(ctx, pid)
		if err != nil {
			continue
		}
		out = append(out, p)
	}

	return out, nil
}

参考