libbpf 开发指南:自动加载BPF程序所需的内核模块

目录

函数原型与解释

代码demo

makefile

cmake

期望输出


函数原型与解释

bool bpf_program__autoload(const struct bpf_program *prog);

参数说明:

  • prog:指向 struct bpf_program 的指针,表示要自动加载内核模块的BPF程序。

返回值:

  • 成功返回 true,失败返回 false。

代码demo

#include <bpf/bpf_helpers.h>
#include <linux/bpf.h>

SEC("kprobe/__x64_sys_getpid")
int bpf_prog1(struct pt_regs *ctx) {
    return 0;
}

char _license[] SEC("license") = "GPL";
#include <stdio.h>
#include <stdlib.h>
#include <bpf/libbpf.h>

int main() {
    struct bpf_object *obj;
    struct bpf_program *prog;
    const char *section_name;

    obj = bpf_object__open_file("example.o", NULL);
    if (!obj) {
        printf("Failed to open BPF object file\n");
        return 1;
    }

    prog = bpf_program__next(NULL, obj);
    if (!prog) {
        printf("Failed to find BPF program\n");
        bpf_object__close(obj);
        return 1;
    }

    section_name = bpf_program__section_name(prog);
    printf("BPF program section name: %s\n", section_name);

    bpf_object__close(obj);
    return 0;
}

makefile

CC=gcc
CFLAGS=-I/usr/include/bpf -I./include
LDFLAGS=-lbpf

all: test

test: test.c
	$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)

clean:
	rm -f test

cmake

cmake_minimum_required(VERSION 2.8)
project(test)

set(CMAKE_C_FLAGS "-I/usr/include/bpf -I./include")

add_executable(test test.c)
target_link_libraries(test bpf)

期望输出

make

./demo

BPF program loaded successfully

猜你喜欢

转载自blog.csdn.net/qq_32378713/article/details/131570190