diff --git a/internal/procstatm/procstatm.go b/internal/procstatm/procstatm.go new file mode 100644 index 0000000..1f00966 --- /dev/null +++ b/internal/procstatm/procstatm.go @@ -0,0 +1,37 @@ +package procstatm + +import ( + "fmt" + "os" +) + +// Statm provides statistics of memory. +type Statm struct { + Size uint + Resident uint + Share uint + Text uint + Lib uint + Data uint + Darty uint +} + +var zero = Statm{} + +// Get gets Statm for process (pid). +// pid should be process id (integer) or string ("self" or so). +func Get(pid interface{}) (Statm, error) { + name := fmt.Sprintf("/proc/%s/statm", pid) + f, err := os.Open(name) + if err != nil { + return zero, err + } + defer f.Close() + m := Statm{} + _, err = fmt.Fscanf(f, "%d %d %d %d %d %d %d", + &m.Size, &m.Resident, &m.Share, &m.Text, &m.Lib, &m.Data, &m.Darty) + if err != nil { + return zero, fmt.Errorf("failed to scan %s: %w", name, err) + } + return m, nil +} diff --git a/phymem.go b/phymem.go index e6089fc..7b3d1da 100644 --- a/phymem.go +++ b/phymem.go @@ -1,4 +1,5 @@ // +build !windows +// +build !linux package phymem diff --git a/phymem_linux.go b/phymem_linux.go new file mode 100644 index 0000000..65e9934 --- /dev/null +++ b/phymem_linux.go @@ -0,0 +1,15 @@ +package phymem + +import "github.com/koron-go/phymem/internal/procstatm" + +// for test. +const providedCurrent = true + +// Current get physical memory which used by current process. +func Current() (uint, error) { + m, err := procstatm.Get("self") + if err != nil { + return 0, err + } + return m.Resident * 4096, nil +}