Skip to content

Commit d76446a

Browse files
committed
Improve comm output
1 parent 433aeed commit d76446a

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

output.go

+20-11
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
package main
2323

2424
import (
25+
"bytes"
2526
"fmt"
2627
"sort"
2728
"strings"
@@ -32,11 +33,12 @@ import (
3233
)
3334

3435
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"
4042
)
4143

4244
// 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) {
6668
Packets: val.Packets,
6769
Bitrate: 8 * float64(val.Bytes) / dur,
6870
Pid: key.Pid,
69-
Comm: byte2String(key.Comm[:]),
71+
Comm: comm2String(key.Comm[:]),
7072
})
7173
}
7274

@@ -140,16 +142,23 @@ func outputJSON(m []statEntry) {
140142
fmt.Printf("%v\n", string(out))
141143
}
142144

143-
// byte2String converts a slice of int8 to a string.
145+
// comm2String converts a byte slice to a string, trimming any null bytes.
144146
//
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+
149156
b := make([]byte, len(bs))
150157
for i, v := range bs {
151158
b[i] = byte(v)
152159
}
153160

161+
b = bytes.Trim(b, "\x00")
162+
154163
return string(b)
155164
}

0 commit comments

Comments
 (0)