Golang os / exec, real-time memory usage

I use Linux, go and os / exec to run some commands. I want to know the process of using memory in real time. This means that I can request memory usage at any time after the process starts, and not just after it starts.

(This is why the answer in Measuring the use of an executable using golang is not an option for me)

For instance:

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

I do not need a very accurate value, but it would be great if the error range was lower than, say, 10 megabytes.

Is there a way to do this, or do I need some kind of command line trick?

+4
source share
1 answer

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
}

PSS ( ) PID, KB. , /proc.

3.0.13.

+5

Source: https://habr.com/ru/post/1568801/


All Articles