当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > linux下通过go语言获得系统进程cpu使用情况的方法

linux下通过go语言获得系统进程cpu使用情况的方法

2017年12月08日  | 移动技术网IT编程  | 我要评论

本文实例讲述了linux下通过go语言获得系统进程cpu使用情况的方法。分享给大家供大家参考。具体分析如下:

这段代码通过linux的系统命令 ps来分析cpu的使用情况,代码如下:

复制代码 代码如下:
package main
import (
    "bytes"
    "log"
    "os/exec"
    "strconv"
    "strings"
)
type process struct {
    pid int
    cpu float64
}
func main() {
    cmd := exec.command("ps", "aux")
    var out bytes.buffer
    cmd.stdout = &out
    err := cmd.run()
    if err != nil {
        log.fatal(err)
    }
    processes := make([]*process, 0)
    for {
        line, err := out.readstring('\n')
        if err!=nil {
            break;
        }
        tokens := strings.split(line, " ")
        ft := make([]string, 0)
        for _, t := range(tokens) {
            if t!="" && t!="\t" {
                ft = append(ft, t)
            }
        }
        log.println(len(ft), ft)
        pid, err := strconv.atoi(ft[1])
        if err!=nil {
            continue
        }
        cpu, err := strconv.parsefloat(ft[2], 64)
        if err!=nil {
            log.fatal(err)
        }
        processes = append(processes, &process{pid, cpu})
    }
    for _, p := range(processes) {
        log.println("process ", p.pid, " takes ", p.cpu, " % of the cpu")
    }
}

希望本文所述对大家的go语言程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网