Created
November 17, 2017 22:59
-
-
Save crosbymichael/7da3aa6541e4e60f6cecdfe3ace4ccfa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"flag" | |
"fmt" | |
"log" | |
"os" | |
"sort" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
flag.Parse() | |
if err := run(); err != nil { | |
log.Fatal(err) | |
} | |
} | |
func run() error { | |
pid, err := strconv.Atoi(flag.Arg(0)) | |
if err != nil { | |
return err | |
} | |
smaps, err := getMaps(pid) | |
if err != nil { | |
return err | |
} | |
sorted := keys(smaps) | |
for _, k := range sorted { | |
fmt.Printf("%s %d\n", k, smaps[k]) | |
} | |
return nil | |
} | |
func getMaps(pid int) (map[string]int, error) { | |
f, err := os.Open(fmt.Sprintf("/proc/%d/smaps", pid)) | |
if err != nil { | |
return nil, err | |
} | |
defer f.Close() | |
var ( | |
smaps = make(map[string]int) | |
s = bufio.NewScanner(f) | |
) | |
for s.Scan() { | |
var ( | |
fields = strings.Fields(s.Text()) | |
name = fields[0] | |
) | |
if len(fields) < 2 { | |
continue | |
} | |
n, err := strconv.Atoi(fields[1]) | |
if err != nil { | |
continue | |
} | |
smaps[name] += n | |
} | |
if err := s.Err(); err != nil { | |
return nil, err | |
} | |
return smaps, nil | |
} | |
func keys(smaps map[string]int) []string { | |
var o []string | |
for k := range smaps { | |
o = append(o, k) | |
} | |
sort.Strings(o) | |
return o | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment