How can i get the memory used by each process in linux system

From proc folder how to read the each processes and its used ram memory ,

How is this related to Go?

func (p *Unixprocess) fillFromStatus() error {
return p.fillFromStatusWithContext(context.Background())
}

func (p *Unixprocess) fillFromStatusWithContext(ctx context.Context) error {
pid := p.pid
statPath := memory.HostProc(strconv.Itoa(int(pid)), “status”)
contents, err := ioutil.ReadFile(statPath)
if err != nil {
return err
}
lines := strings.Split(string(contents), “\n”)

//p.memInfo = &MemoryInfoStat{}
 p.meminfo= &MemInfoStat{}
for _, line := range lines {
	tabParts := strings.SplitN(line, "\t", 2)
	if len(tabParts) < 2 {
		continue
	}
	value := tabParts[1]
	switch strings.TrimRight(tabParts[0], ":") {

	case "PPid", "Ppid":
		pval, err := strconv.ParseInt(value, 10, 32)
		if err != nil {
			return err
		}
		p.ppid = int(pval)

	case "VmRSS":
		value := strings.Trim(value, " kB") // remove last "kB"
		v, err := strconv.ParseUint(value, 10, 64)
		if err != nil {
			return err
		}
		p.meminfo.RSS=v* 1024
		//p.memInfo.RSS = v * 1024
	case "VmSize":
		value := strings.Trim(value, " kB") // remove last "kB"
		v, err := strconv.ParseUint(value, 10, 64)
		if err != nil {
			return err
		}
		p.meminfo.VMS = v * 1024
	case "VmSwap":
		value := strings.Trim(value, " kB") // remove last "kB"
		v, err := strconv.ParseUint(value, 10, 64)
		if err != nil {
			return err
		}
		p.meminfo.Swap = v * 1024
	}
	}

return nil

}

I am unable to get the required output from main function

Which library provides Unixprocess?

1 Like

It is the struct name Unixprocess.

type Unixprocess struct {
pid int
name string
ppid int
binary string
state rune
status string
pgrp int
sid int
meminfo *MemInfoStat
}

i want to read the each running processes of linux system and its cpu usage and memory usage using go language

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.