-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathswapview.go
144 lines (119 loc) · 2.28 KB
/
swapview.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"strconv"
"strings"
"sync"
// "time"
)
type Info struct {
Pid int
Size int64
Comm string
}
var (
nullBytes = []byte{0x0}
emptyBytes = []byte(" ")
swapPrefix = "Swap:"
)
func main() {
slist := GetInfos()
sort.Slice(slist, func(i, j int) bool {
return slist[i].Size < slist[j].Size
})
fmt.Printf("%7s %9s %s\n", "PID", "SWAP", "COMMAND")
var total int64
for _, v := range slist {
fmt.Printf("%7d %9s %s\n", v.Pid, FormatSize(v.Size), v.Comm)
total += v.Size
}
fmt.Printf("Total: %10s\n", FormatSize(total))
}
func GetInfos() (list []Info) {
f, _ := os.Open("/proc")
defer f.Close()
names, err := f.Readdirnames(0)
if err != nil {
log.Fatalf("read /proc: %v", err)
}
length := len(names)
list = make([]Info, 0, length)
infoCh := make(chan Info, length)
wg := &sync.WaitGroup{}
wg.Add(length)
go func() {
defer close(infoCh)
defer wg.Wait()
for _, name := range names {
go GetInfo(name, infoCh, wg)
}
}()
for v := range infoCh {
list = append(list, v)
}
return
}
func GetInfo(name string, infoCh chan<- Info, wg *sync.WaitGroup) {
defer wg.Done()
pid, err := strconv.Atoi(name)
if err != nil {
return
}
info := Info{
Pid: pid,
}
var bs []byte
bs, err = ioutil.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid))
if err != nil {
return
}
if bytes.HasSuffix(bs, nullBytes) {
bs = bs[:len(bs)-1]
}
info.Comm = string(bytes.Replace(bs, nullBytes, emptyBytes, -1))
bs, err = ioutil.ReadFile(fmt.Sprintf("/proc/%d/smaps", pid))
if err != nil {
return
}
var total, size int64
var b string
r := bufio.NewScanner(bytes.NewReader(bs))
for r.Scan() {
b = r.Text()
if !strings.HasPrefix(b, swapPrefix) {
continue
}
x := strings.Split(b, string(emptyBytes))
size, err = strconv.ParseInt(x[len(x)-2], 10, 64)
if err != nil {
return
}
total += size
}
// No swap pid info should be ignored.
if total == 0 {
return
}
info.Size = total * 1024
infoCh <- info
return
}
var units = []string{"", "K", "M", "G", "T"}
func FormatSize(s int64) string {
if s <= 1100 {
return fmt.Sprintf("%dB", s)
}
unit := 0
f := float64(s)
for unit < len(units) && f > 1100.0 {
f /= 1024.0
unit++
}
return fmt.Sprintf("%.1f%siB", f, units[unit])
}