1 Star 1 Fork 1

up-zero/gotool

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
ps_linux.go 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
GetcharZp 提交于 2023-10-26 16:12 +08:00 . fix linux PsByName find by /proc
//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
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/up-zero/gotool.git
git@gitee.com:up-zero/gotool.git
up-zero
gotool
gotool
main

搜索帮助