libbpf 开发指南:获取与给定 eBPF 链接关联的文件描述符

目录

函数原型与解释

代码demo

makefile

cmake

期望输出


函数原型与解释

LIBBPF_API int bpf_link__fd(const struct bpf_link *link);

参数说明:

  • link:一个指向 bpf_link 结构的指针,表示要操作的 eBPF 链接。

返回值:一个整数,表示与给定 eBPF 链接关联的文件描述符。如果发生错误,将返回负数。

代码demo

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

SEC("kprobe/__x64_sys_getpid")
int bpf_prog1(struct pt_regs *ctx) {
    bpf_printk("sys_getpid called\n");
    return 0;
}

char _license[] SEC("license") = "GPL";
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/bpf.h>
#include <bpf/bpf.h>
#include <bpf/libbpf.h>

int main(int argc, char **argv) {
    if (argc != 2) {
        fprintf(stderr, "Usage: %s <bpf_program.o>\n", argv[0]);
        return 1;
    }

    const char *bpf_program_path = argv[1];
    struct bpf_object *obj = NULL;
    struct bpf_program *prog = NULL;
    struct bpf_link *link = NULL;

    if (bpf_prog_load(bpf_program_path, BPF_PROG_TYPE_KPROBE, &obj, &prog)) {
        fprintf(stderr, "Error loading BPF program: %s\n", strerror(errno));
        return 1;
    }

    link = bpf_program__attach(prog);
    if (libbpf_get_error(link)) {
        fprintf(stderr, "Error attaching BPF program: %s\n", strerror(errno));
        return 1;
    }

    int fd = bpf_link__fd(link);
    if (fd < 0) {
        fprintf(stderr, "Error getting BPF link file descriptor: %s\n", strerror(errno));
        return 1;
    }

    printf("BPF link file descriptor: %d\n", fd);

    // Wait for user input to disconnect and destroy the link
    printf("Press Enter to disconnect and destroy the BPF link...\n");
    getchar();

    bpf_link__destroy(link);
    bpf_object__unload(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 link file descriptor:3
Press Enter to disconnect and destroy the BPF link...

猜你喜欢

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