22
22
package main
23
23
24
24
import (
25
+ "bytes"
25
26
"fmt"
26
27
"sort"
27
28
"strings"
@@ -32,11 +33,12 @@ import (
32
33
)
33
34
34
35
const (
35
- Bps float64 = 1.0
36
- Kbps = 1000 * Bps
37
- Mbps = 1000 * Kbps
38
- Gbps = 1000 * Mbps
39
- Tbps = 1000 * Gbps
36
+ Bps float64 = 1.0
37
+ Kbps = 1000 * Bps
38
+ Mbps = 1000 * Kbps
39
+ Gbps = 1000 * Mbps
40
+ Tbps = 1000 * Gbps
41
+ KernelComm = "kernel"
40
42
)
41
43
42
44
// processMap generates statEntry objects from an ebpf.Map using the provided start time.
@@ -66,7 +68,7 @@ func processMap(m *ebpf.Map, start time.Time) ([]statEntry, error) {
66
68
Packets : val .Packets ,
67
69
Bitrate : 8 * float64 (val .Bytes ) / dur ,
68
70
Pid : key .Pid ,
69
- Comm : byte2String (key .Comm [:]),
71
+ Comm : comm2String (key .Comm [:]),
70
72
})
71
73
}
72
74
@@ -140,16 +142,23 @@ func outputJSON(m []statEntry) {
140
142
fmt .Printf ("%v\n " , string (out ))
141
143
}
142
144
143
- // byte2String converts a slice of int8 to a string.
145
+ // comm2String converts a byte slice to a string, trimming any null bytes .
144
146
//
145
- // It takes a slice of int8 as a parameter, creates a new slice of byte of the same length,
146
- // copies the values of the int8 slice to the byte slice, and converts the byte slice to a string.
147
- // The resulting string is then returned.
148
- func byte2String (bs []int8 ) string {
147
+ // It takes a byte slice as its parameter and returns a string.
148
+ // If the byte slice is empty, the function returns the string "kernel".
149
+ // Otherwise, it creates a new byte slice, copies the input byte slice into it,
150
+ // trims any null bytes from the end of the slice, and returns the result as a string.
151
+ func comm2String (bs []int8 ) string {
152
+ if len (bs ) == 0 {
153
+ return KernelComm
154
+ }
155
+
149
156
b := make ([]byte , len (bs ))
150
157
for i , v := range bs {
151
158
b [i ] = byte (v )
152
159
}
153
160
161
+ b = bytes .Trim (b , "\x00 " )
162
+
154
163
return string (b )
155
164
}
0 commit comments