简体   繁体   English

Golang os / exec,实时内存使用情况

[英]Golang os/exec, realtime memory usage

I'm using Linux, go, and os/exec to run some commands. 我正在使用Linux,go和os / exec来运行一些命令。 I want to know a process' realtime memory usage. 我想知道一个进程'实时内存使用情况。 That means that I can ask for memory usage anytime after I start the process, not just after it ran. 这意味着我可以在启动进程后随时询问内存使用情况,而不仅仅是在运行之后。

(That's why the answer in Measuring memory usage of executable run using golang is not an option for me) (这就是为什么使用golang测量可执行文件的内存使用量的答案对我来说不是一个选项)

For example: 例如:

cmd := exec.Command(...)
cmd.Start()
//...
if cmd.Memory()>50 { 
    fmt.Println("Oh my god, this process is hungry for memory!")
}

I don't need very precise value, but it would be great if it's error range is lower than, say, 10 megabytes. 我不需要非常精确的值,但如果它的误差范围低于10兆字节则会很好。

Is there a go way to do that or I need some kind of command line trick? 有没有办法做到这一点,或者我需要某种命令行技巧?

Here is what I use on Linux: 这是我在Linux上使用的内容:

func calculateMemory(pid int) (uint64, error) {

    f, err := os.Open(fmt.Sprintf("/proc/%d/smaps", pid))
    if err != nil {
        return 0, err
    }
    defer f.Close()

    res := uint64(0)
    pfx := []byte("Pss:")
    r := bufio.NewScanner(f)
    for r.Scan() {
        line := r.Bytes()
        if bytes.HasPrefix(line, pfx) {
            var size uint64
            _, err := fmt.Sscanf(string(line[4:]), "%d", &size)
            if err != nil {
                return 0, err
            }
            res += size
        }
    }
    if err := r.Err(); err != nil {
        return 0, err
    }

    return res, nil
}

This function returns the PSS (Proportional Set Size) for a given PID, expressed in KB. 此函数返回给定PID的PSS(比例集大小) ,以KB表示。 If you have just started the process, you should have the rights to access the corresponding /proc file. 如果刚刚启动该过程,则应该有权访问相应的/ proc文件。

Tested with kernel 3.0.13. 用内核3.0.13测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM