drju37335 2012-02-21 12:58
浏览 161

如何从其pid获取过程详细信息

I have maintained a list of pids of processes currently running on my system(Linux) from this now it would be great if i can get the process details from this pid i have come over syscall.Getrusage() in golang but i am not getting desired results. Does anyone have idea related to it

  • 写回答

4条回答 默认 最新

  • dougu9895 2012-02-21 15:26
    关注

    You could look at /proc/[pid]/stat. For example, using Go 1,

    package main
    
    import (
        "fmt"
        "io/ioutil"
        "os"
        "strconv"
    )
    
    func Pids() ([]int, error) {
        f, err := os.Open(`/proc`)
        if err != nil {
            return nil, err
        }
        defer f.Close()
        names, err := f.Readdirnames(-1)
        if err != nil {
            return nil, err
        }
        pids := make([]int, 0, len(names))
        for _, name := range names {
            if pid, err := strconv.ParseInt(name, 10, 0); err == nil {
                pids = append(pids, int(pid))
            }
        }
        return pids, nil
    }
    
    func ProcPidStat(pid int) ([]byte, error) {
        // /proc/[pid]/stat
        // https://www.kernel.org/doc/man-pages/online/pages/man5/proc.5.html
        filename := `/proc/` + strconv.FormatInt(int64(pid), 10) + `/stat`
        return ioutil.ReadFile(filename)
    }
    
    func main() {
        pids, err := Pids()
        if err != nil {
            fmt.Println("pids:", err)
            return
        }
        if len(pids) > 0 {
            pid := pids[0]
            stat, err := ProcPidStat(pid)
            if err != nil {
                fmt.Println("pid:", pid, err)
                return
            }
            fmt.Println(`/proc/[pid]/stat:`, string(stat))
        }
    }
    

    Output:

    /proc/[pid]/stat: 1 (init) S 0 1 1 0 -1 4202752 11119 405425 21 57 78 92 6643 527 20 0 1 0 3 24768512 563 184467440737095
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line