020.eBPF用户态如何传递pid给内核态

这个专题学完

你就知道用户态如何给ebpf端传承

后面自己写工具

根据需求选择用哪种方式


一般来说

监测工具只监测某个进程

而监测的工作是由eBPF端负责的

要监测的进程pid在用户态

就涉及到用户态给eBPF端传递数据的问题

用户态给eBPF端传数据,有三种方式

1、attach时传

image

2、rodata方式

ebpf端定义一个全局变量

const volatile int target_pid = 0;

用户态赋值

skel->rodata->target_pid = pid;

3、map方式(一般商用软件都是用这种方式)

ebpf端定义一个map

struct {
    __uint(type, BPF_MAP_TYPE_HASH);
    __uint(max_entries, 128);
    __type(key, u32);   // pid
    __type(value, u8); // dummy
} target_pids SEC(".maps");

用户态赋值

uint8_t one = 1;

        int err = bpf_map__update_elem(
                skel->maps.target_pids,
                &pid,
                sizeof(pid),
                &one,
                sizeof(one),
                BPF_ANY
        );

        if (err) {
            fprintf(stderr, "update target_pids failed: %d\n", err);
        }

这种方式比前面两种还有一个优势:支持多个pid

image

如何查看map中的值呢?

sudo bpftool map dump name target_pids

他们的对比

image

posted @ 2026-06-02 00:40  BlackSnow  阅读(9)  评论(0)    收藏  举报