map_xxx_elem (v3.19)
Summary
map_lookup_elem
Retrieves the value associated with a given key from a map.map_update_elem
Updates the value associated with a given key in a map. If the key does not exist, it can add the key-value pair.map_delete_elem
Removes the key-value pair associated with a given key from a map.
Kernel Code
Summary:
A hash map
my_map
is defined with keys and values of type__u32
.The eBPF program looks up a value with key
1
, updates it to42
, and then deletes it.bpf_printk
is used to print messages to the kernel log, which can be viewed usingdmesg
.
Userland Code
Summary:
The userland program loads the BPF object file using
bpf_object__open
andbpf_object__load
.It retrieves the file descriptor for the BPF program using
bpf_program__fd
.A hash map is created using
bpf_create_map_xattr
.A raw socket is created and the BPF program is attached to it using
setsockopt
.The program waits for user input to keep the BPF program running, allowing it to execute.
Resources are cleaned up when the program exits.
Conclusions
The example demonstrates the use of
map_lookup_elem
,map_update_elem
, andmap_delete_elem
in a simple eBPF program.The userland code uses full libbpf functions to load, create maps, attach programs, and manage resources without using the skeleton generated by
bpftool
.The output from
bpf_printk
can be viewed usingbpftool
by runningbpftool prog trace
.
Last updated